Question:
C Programming, how to split a string in two?
Sanghee Elf
2011-10-20 16:31:18 UTC
I have 2 different cases where I want to split a string in two but I don't know how to do it. In one case, the string is always 6 characters, and I want to split it into two strings of 3 characters. For example: string abcdef becomes string abc and string def

The other case is a little less simple. The string can be any of the following and I'd like to split them so that they are two strings like on the right side:
LL : L L
ll : l l
Ll : L l
lL : l L
lala : la la
laL : la L
lal : la l
lla : l la
Lla : L la
So the final strings will be either L, l, or la

Can anyone give some advice? I can provide more info if needed :)
Three answers:
cja
2011-10-21 06:58:26 UTC
You should create a general purpose string split function, then you can call it however you want; applying the rules you've shown above, for example. See below for how I did it. Normally I don't like a function to allocate memory on behalf of the caller, but I did that here. Whatever you do, you need to be careful with memory management with this problem.



#include

#include

#include



typedef enum { false = 0, true } bool;

bool splitAt(const char *s0, size_t x, char **s1, char **s2);



int main(int argc, char *argv[]) {

    char *s1, *s2;



    if (splitAt("abcdef", 3, &s1, &s2) == true) {

        printf("%s %s\n", s1, s2);

        free(s1); free(s2);

    }

    if (splitAt("Lla", 1, &s1, &s2) == true) {

        printf("%s %s\n", s1, s2);

        free(s1); free(s2);

    }

    return 0;

}





bool splitAt(const char *s0, size_t x, char **s1, char **s2) {

    bool splitOk;

    const char *p;



      /*

        * If the split point is within the string, we may proceed.

        */

      if ((splitOk = (x < (strlen(s0) - 1))) == true) {

          /*

            * Allocate space for the 1st substring, and copy it to s1

            */

          *s1 = calloc(x + 1, sizeof(char));

          strncpy(*s1, s0, x);



          /*

            * Set p to point to the start of the 2nd substring, which

            * is the remainder of s0.

            */

          p = s0 + x;



          /*

            * Allocate space for the 2nd substring, and copy it to s2

            */

          *s2 = calloc(strlen(p) + 1, sizeof(char));

          strcpy(*s2, p);

      }

      return splitOk;

}



#if 0



Program output:



abc def

L la



#endif
?
2016-10-14 07:53:42 UTC
listed right here are some tricks. You couls use the string function 'IndexOf' to get the situation of the gap i.e. sSentance.IndexOf(' '). Then use Substring. i desire to advise you examine up on them and play around with them.
2011-10-20 16:33:09 UTC
well you could always ask sollux.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...