Kreuzade
Kreuzade

Reputation: 777

Split a string into two based on char location

I need to split a string into string based on the location of a character. So that:

str1 = "hello?world" is str1 = "hello" and str2 = "world"

This is what I have so far:

    char    str1[100] = "hello?world";
    char    str2[100];
    char    *p;

    p = strpbrk(str1, "?");
    strcpy(&str2, p);

    strcspn(str1, '?');

I get errors when trying to copy the characters after 'p' to str2. There has got to be a better and functional way. Can someone help me out? Many thanks...

Upvotes: 2

Views: 3252

Answers (4)

Neil
Neil

Reputation: 2438

Use strtok(). Follow the link to see an example.

Do something like this:

   char    src[] = "hello?world";
   char    str1[100];
   char    str2[100];
   char    *p;

   p = strtok(src, "?");
   strcpy(str1, p);

   p = strtok(NULL, "?");
   strcpy(str2, p);

Upvotes: 1

Simon MILHAU
Simon MILHAU

Reputation: 214

I don't know so much stdlib strings functions but you can do this (your strings will be "secure", i mean you will not have to allocate too much bytes but just the bytes needed that's why the code will be a bit long):

int main()
{
  char *tmp;
  char *s1;
  char *s2;
  char delim;
  int i;
  int j;

  tmp = strdup("hello?world");
  delim = '?';
  i = 0;
  while (s1[i] != delim)
   i++;
  j = 0;
  s1 = malloc(i + 1);
  while (j < i)
   {
    s1[j] = tmp[j];
    j++;
   }
  s1[j + 1] = '\0';
  j = 0;
  i++;
  while (tmp[i])
   {
    i++;
    j++;
   }
  i = strlen(tmp) - j;
  s2 = malloc(j + 1);
  j = 0;
  while (tmp[i])
   {
    s2[j] = tmp[i];
    j++;
    i++;
   }
  s2[j + 1] = '\0';
}

I hope this will help you.

Upvotes: 1

md5
md5

Reputation: 23707

&str2 is a pointer to an array [100]. You should indeed use the adress of str2. Moreover, the second parameter of strcspn should be "?" (a null-terminated string) instead of '?' (a single character).
Besides, the following code works fine:

#include <stdio.h>
#include <string.h>

char s[] = "hello?world"; /* source string */

char s1[100] = ""; /* first part */
char s2[100] = ""; /* second part */

char *tmp = strchr(s, '?');

if (tmp != NULL) {
    *tmp = '\0';
    strcpy(s1, s);
    strcpy(s2, tmp+1);
}

puts(s1);
puts(s2);

Upvotes: 3

Daniel Fischer
Daniel Fischer

Reputation: 183968

This

strcspn(str1, '?');

is an error, strcspn's second parameter is a const char*, passing a character constant there is almost certain to cause undefined behaviour and a segmentation fault (Your programme is very unlikely to have the address 63 (ASCII value of '?') in its address space, and if it has, it's unlikely to point to a 0-terminated character array).

p = strpbrk(str1, "?");
strcpy(str2, p+1);

ought to work. If you want to end str1 at the '?', *p = 0; overwrites the '?' with a 0. But of course generally, you should verify that strpbrk doesn't return NULL before using p.

Upvotes: 2

Related Questions