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??
CodePudding user response:
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]
CodePudding user response:
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;
}