1

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??

3
  • What exactly are your parameters to strncat supposed to mean? How is str[i]+4 gonna be a useful value for length? Commented Feb 22, 2022 at 7:32
  • Your example output is not splitting the string at all. It extracts substrings of length 4. Commented Feb 22, 2022 at 7:33
  • regarding: for(int i=0;i<strlen(str);i++){ variable i is an integer and the returned value from strlen() is a size_t. the code goes downhill from there Commented Feb 22, 2022 at 19:46

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.