How to append parts of a string in a char array? - c

I need to split the string of n size and append in an array.
For example:
input:
abcdefghi
4
output:
[abcd,bcde,cdef,defg,efgh,fghi]
My code giving wrong answer:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
for(int i=0;i<strlen(str);i++){
strncat(result, str, str[i]+4);
}
printf("result: %s\n ", result);
}
My output:
abcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgi
What mistake have I made??

Would you please try the following:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
int n = 4;
int i, j;
char *p = result; // pointer to the string to write the result
*p++ = '['; // left bracket
for (i = 0; i < strlen(str) - n + 1; i++) { // scan over "str"
for (j = i; j < i + n; j++) { // each substrings
*p++ = str[j]; // write the character
}
*p++ = i == strlen(str) - n ? ']' : ','; // write right bracket or a comma
}
*p++ = '\0'; // terminate the string with a null character
printf("result: %s\n", result); // show the result
return 0;
}
Output:
result: [abcd,bcde,cdef,defg,efgh,fghi]

Might this work for you?
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "abcdefghijklmno";
char result[100][100];
int nSplit = 4; //Split size
int nLength = strlen (str); //Lenth of the string
int nTotalString = nLength - nSplit; //total possibilities
int nStrCount = 0;
for (int i = 0; i <= nTotalString ; i ++)
{
for (int j = 0; j < nSplit; j++)
result[nStrCount][j] = str[i + j];
nStrCount++;
}
//print array
printf ("result:[");
for (int k = 0; k < nStrCount; k++)
printf ("\"%s\" ", result[k]);
printf ("]");
return 0;
}

Related

How to combine 2 arrays without using strncat?

I currently try to combine 2 arrays without using strncat. The following code doesnt work and the problem lies in one of the for loops. I guess that some of these boundaries are wrong, but I'm not capable of finding the mistake:
#include <stdio.h>
int main() {
char text1[] = {"Hello"};
char text2[] = {", how are you?"};
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for(int k = 0; k<count2; k++) {
result[k+1+count1] = text2[k];
}
for(int j = 0; j<count1+count2; j++) {
printf(" %s", result[j]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char text1[] = "Hello"; //correct way to initialize string
char text2[] = ", how are you?";
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for(int k = 0; k<count2; k++) {
result[k+count1] = text2[k]; //k + 1 + count1 causes bug
}
result[count1+count2] = '\0' ; //adding NULL char at the end
printf("%s\n" , result) ; //printing the string using %s
return 0;
}
Instead of defining the size of your result array as 100, you should define it equal to the sum of the length of both the input arrays.
Also, the format specifier should be %c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char text1[] = {"Hello"};
char text2[] = {", how are you?"};
int count1 = strlen(text1);
int count2 = strlen(text2);
char *result = malloc(count1 + count2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for (int i = 0; i < count2; i++) {
result[count1 + i] = text2[i];
}
for (int i = 0; i < count1 + count2; i++) {
printf("%c", result[i]);
}
return 0;
}
You do it with fewer variables and a lot less code. You've lost track of what is what and 'skip' a space with 'k+1+count1'... Then try to print, in a loop, characters using a %s format specifier. Too complicated!
#include <stdio.h>
int main() {
char result[100], text1[] = "Hello", text2[] = ", how are you?";
int i = 0, j = 0;
while( (result[ i ] = text1[ i ] ) != '\0' )
i++;
while( (result[ i ] = text2[j++] ) != '\0' )
i++;
puts( result );
return 0;
}
The output is as expected.
So this is the code that works and i've explained each line after the code snippet.
#include <stdio.h>
#include<string.h>
int main() {
char text1[] = "Hello";
char text2[] = ", how are you?";
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i=0 ; i<(count1+count2); i++){
if(i<count1)
{
result[i]= text1[i];
}
else{
result[i]=text2[i-count1];
}
}
for(int j = 0; j<count1+count2; j++) {
printf("%c", result[j]);
}
return 0;
}
In the first loop, you'd see i'm iterating from 0 to the sum of both the string sizes as i'm assuming that there's a single large string instead of two seperate ones.
As you mentioned that count1 is the size of text1 and count2 as the size of text2, so the logic i used here is that as long as the value of i is lesser than the size of the text1, I'm taking the characters from that position in the text and assigning it to the result string, then once i exceeds that, i'm subtracting the count1 value from the i value as it will again take characters from the 0th position from the text2 and assigning it to the result string.
I would also like to also mention that when you initialise a character array as a string, you just use " ", not {" "} and also when you're printing a character array so you use "%c" not "%s" unless you're printing out a string which you do use "%s" and if so, you can remove the looping statement.
Hope this helps!

Program to print all substrings of a given string

I am having trouble creating an algorithm that prints all substrings of a given string. This is my implementation now:
#include <stdio.h>
#include <string.h>
// Function to print all sub strings
void subString(char str[], int n)
{
// Pick starting point
for (int len = 1; len <= n; len++)
{
// Pick ending point
for (int i = 0; i <= n - len; i++)
{
// Print characters from current
// starting point to current ending
// point.
int j = i + len - 1;
for (int k = i; k <= j; k++) {
char data[n];
sprintf(data, "%d", str[k]);
printf("%s\n", data);
}
}
}
}
// Driver program to test above function
int main()
{
char str[] = "abc";
subString(str, strlen(str));
return 0;
}
My code is not converting integers to strings. Could someone help me figure out what's wrong?
The logic seems basically fine, but the formatting doesn't make much sense as this prints the digit values for each character and adds a newline for each print call. If you print the characters directly using %c formatting and only print a newline once you've emitted a full substring you'll have a more sensible result.
#include <stdio.h>
#include <string.h>
void subString(char *str, int n)
{
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
for (int j = i; j <= i + len - 1; j++)
{
putchar(str[j]);
}
puts("");
}
}
}
int main()
{
char str[] = "abc";
subString(str, strlen(str));
return 0;
}
Output:
a
b
c
ab
bc
abc
A little nitpick: I'd suggest calling this function printSubStrings since it produces a side effect. The name subString doesn't seem to match the contract particularly well.
You can also use the "%.*s" format to extract the substring chunk you want instead of the innermost loop:
void print_substrings(char *str, int n)
{
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
printf("%.*s\n", len, str + i);
}
}
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
string str;
cin >> str;
for (int i = 0; i < str.size(); i++) {
for (int len = 1 ; len <= str.size() - i; len++)
{
cout << str.substr(i, len) << endl; // prints substring from starting index i till length len
}
}
return 0;
}
Input:
abcd
Output:
a
ab
abc
abcd
b
bc
bcd
c
cd
d

How to divide a string to substring and assign another substring?

I want to divide *eString to substrings. Substrings should be like that:
y_{1} = y_{1}y_{m+1}y_{2m+1}...
y_{2} = y_{2}y_{m+2}y_{2m+2}...
y_{m} = y_{m}y_{2m}y_{3m}...
where y is the element of *eString, and y is the substring of these elements.
For instance, if an user expects the key length which is 5, there should be (string size / 5) substrings. y_{1} has to contain the fist element of each divided substring. So, how can I implement this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHA 26
char *ReadFile(char *);
int main(int argc, char *argv[])
{
double frequency[ALPHA] = {0};
int c = 0;
int keylen = 0;
int counter = 0;
double indexofCoincidence = 0,total = 0;
const char *eString = ReadFile("cipher.txt");
int len = 0;
if (eString) {
puts("The encrypted text is:");
puts(eString);
puts("");
len = strlen(eString);
printf("The length of text is %d\n",len);
}
puts("");
while(eString[c]!= '\0'){
if(eString[c]>= 'a' && eString[c]<='z')
frequency[eString[c]-'a']++;
c++;
}
puts("The letters frequencies are :\n");
for(c=0; c<ALPHA;c++){
if(frequency[c]!= 0)
printf("%c : %.3f\t",c+'a',(frequency[c]/len));
total += (frequency[c]*(frequency[c]-1));
}
indexofCoincidence = (total/((len)*(len-1)));
printf("\n\nIndex of Coincidence : %.3f\n",indexofCoincidence);
if(indexofCoincidence < 0.060){
printf("\nIt looks like randomly.\n");
}
printf("Enter the your expected key length : ");
scanf("%d",keylen);
printf("\n");
char *y;
while(counter != keylen)
{
for(int i = 0; i<(len/keylen);i++){
y[counter] = *eString();
}
counter++
}
return EXIT_SUCCESS;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *eString = "The quick brown fox jumps over the lazy dog";
int keylen = 5;
int len = strlen(eString);
int y_len = (len + keylen) / keylen + 1;
int i,j;
char **y = malloc(keylen * sizeof(*y));
for(i=0; i < keylen; ++i){
y[i] = malloc(y_len * sizeof(**y));
}
char *p = eString;
i = j = 0;
while(*p){
y[i % keylen][j] = *p++;
y[i % keylen][j+1] = 0;
if(++i % keylen == 0)
++j;
}
//check print & deallocate
for(i = 0; i < keylen; ++i){
printf("y_{%d} : %s\n", i+1, y[i]);
free(y[i]);
}
free(y);
return 0;
}

C - strcat in for loop

I m writing a little C program and want to know why my output in the console is "0", "0" [...]? The output i expect is "ab", "ac", [...].
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
int j;
char string[] = "abc";
char output[8];
int length = size(&string[0]);
for(i=0; i<length; i++) {
for(j=0; j<length; j++){
char a = string[i];
strcat(output, &a);
char b = string[j];
strcat(output, &b);
printf("%c\n", output);
}
}
return 0;
}
Mistake #1. You have not initialised output[] so strcat() will not validly find a nul terminator to append to.
output[0] = 0;
Mistake #2. strcat() isn't the right way of appending chars anyway.
Mistake #3. Your loop controls aren't right. See below.
Mistake #4. Your length is the size of a char* pointer.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i, j;
char string[] = "abc";
char output[8];
int length = strlen (string); // corrected
for(i=0; i<length-1; i++) { // amended loop
for(j=i+1; j<length; j++) { // amended loop
output[0] = string [i];
output[1] = string [j];
output[2] = 0; // string terminator
printf("%s\n", output); // uses string type not char
}
}
return 0;
}
Program output:
ab
ac
bc
If I have understood correctly what you are trying to do then the program will look the following way
#include <stdio.h>
int main(int argc, char *argv[])
{
char string[] = "abc";
char output[3];
size_t length = sizeof( string ) - 1;
for ( size_t i = 0; i < length; i++ )
{
for ( size_t j = 0; j < length; j++ )
{
if ( i != j )
{
output[0] = string[i];
output[1] = string[j];
output[2] = '\0';
puts( output );
}
}
}
return 0;
}
The output is
ab
ac
ba
bc
ca
cb
If your compiler does not allow to declare variables within the control statement of the loop then you can declare i and j in the beginning of the program.
size_t i, j;
If you want to include combinations like "aa" then you simply may remove the if statement withing the inner loop.
char a = string[i];
strcat(output, &a);
leads to undefined behavior since strcat expects a null terminated string in the second argument. Same thing applies to:
char b = string[j];
strcat(output, &b);
Perhaps you meant to use:
output[0] = a;
output[1] = b;
output[2] = '\0';
Here's the updated for loop:
for(i=0; i<length; i++) {
for(j=0; j<length; j++){
output[0] = a;
output[1] = b;
output[2] = '\0';
printf("%s\n", output);
// ^^ use %s to print a string, not %c.
}
}
If you want to use strcat you must know that it expects a string not a character and there is an important difference, when you pass &a strcat thinks it is the address of a pointer to a string, and you should get most likely a segmentation fault, here I show your own code, modified to use strcat but you don't really need it for this task.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
int j;
char string[] = "abc";
int length = strlen(&string[0]);
for(i = 0 ; i < length ; i++)
{
for(j= i + 1 ; j < length ; j++)
{
/* initialize output to 0 more importantly to have a terminating null byte */
char output[3] = {0};
/*
* create a string and initialize it with 2 char's
* - the first one, the one you want to append to output
* - the second one is required by strcat, to mark the end of the string
*/
char a[2] = {string[i], 0};
strcat(output, a);
/* same as above */
char b[2] = {string[j], 0};
strcat(output, b);
printf("%s\n", output);
}
}
return 0;
}
you could do this without strcat unless you are trying to learn how to use strcat, this is an example of how to do it without strcat.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
int j;
char string[] = "abc";
int length = strlen(&string[0]);
for(i = 0 ; i < length ; i++)
{
for(j= i + 1 ; j < length ; j++)
{
char output[3] = {string[i], string[j], 0};
printf("%s\n", output);
}
}
return 0;
}

How to write a getline function in C?

I know that getline is C++ standard but I need to read a line of digits:
123856
and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:
123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;
But how to make it in C, without a getline?
This is NOT what I want:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
int t[4];
int i;
for(i=0; i<4; i++)
scanf("%d", &t[i]);
for(i=0; i<4; i++)
printf("%d\n", t[i]);
return 0;
}
If I understood you correct, the following should do it:
read the whole line
loop through the string as long as you get digits or the string ends
for every digit, place it's value in your array and increase the index by 1
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
/* If desired, add check for value outside of 0-9 */
array[ i++ ] = c - '0';
...
}
char arr[] = "1234567";
int intarr[10];
int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
intarr[count] = *ptr - '0';
count++;
}
try this
#include <stdio.h>
#include <string.h>
main (int argc, char *argv[])
{
FILE *f;
int i=0;
int j=0;
char output[100];
char* output1[100];
char string[100];
char delims1[] = " ";
char delims2[] = "*";
char* result = NULL;
char* result3 = NULL;
int num;
//for (j=0; j<2; j++)
//{
//printf("%s",delims9[6]);
//}
f = fopen("text.txt","r");
//
while( fgets(string,sizeof(string),f) )
{
result = strtok( string, delims1 );
while( result != NULL )
{
output1[i]=result;
printf("%s\n",output1[i]);
result = strtok( NULL, delims1 );
i++;
}
for (num = 0; num < 100; i++ ) //
{ // Error On this array
printf("%s\n", output1[i]); //
} //
}
printf("\n%d",i/3+1);
return 0 ;
}
Ok, without using any string.
int digits = 123856;
int numofdigits = 1 + floor(log10(digits));
int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
Try the below link... Same question asked here and get solution....
convert an integer number into an array
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}

Resources