Friday, July 31, 2009

In c++ how can I split a given string based on delimeter ?

For ex:


split (string , delimeter);


where split ("hello-world", "-")


returns "hello" and "world".








Thanks in advance.





-Maz

In c++ how can I split a given string based on delimeter ?
Use the function strtok





The function strtok is found in the C string library. It takes two arguments, both arrays of characters (i.e. arguments formally of type char *) which we will informally call strings





The first string is the string that we want to break up into tokens (in our case, that would be inString). The second string consists of a list of delimiters. These are characters which mark divisions between tokens.





When called, the function finds the first token in the string, marks the end of it with a \0 and returns a pointer to the start of that token. In other words, the return value is a string containing just the first token. Once we process that token and have finished with it, we can call strtok again. However this time we call it with a NULL pointer for the first string to indicate that we want the next token of the same original string. We proceed in this manner until strtok returns a NULL pointer, which indicates there are no more tokens left in the string to return.
Reply:#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





char* split(char *str, char deli)


{


char *str2;


for(int i=0;str[i]!=deli;i++);


for(int j=i;str[j]!=NULL;j++)


{


str2[j-i]=str[j+1];


}


str2[j]=NULL;


str[i]=NULL;


return str2;


}





void main()


{


clrscr();


char *a = "Hello-World";


char *b = split(a,'-');


printf("\n a = %s", a);


printf("\n b = %s", b);


//*a will contain "Hello" And *b will contain "World".


getch();


}





i have not tested this code. i just made it ryt here for u only.
Reply:Does 'hello' and 'world' have to be two seperate strings?


If not, then all you have to do is look through the string, and replace the '-' with a space.


You don't need to use any functions on the string.


If it must be 2 strings from ONLY 2 words, then all you have to do is read each letter of a string and copy it to an array. You copy letters until you come to a '-' character. Then you add the number 0 to the array. Skip over the '-' and begin copying into another array until you get to the zero. Add the 0 to the second array. You must add a zero the the arrays because C/C++ strings are zero-terminated. If you tried to print a non-zero-terminated string, then your program could crash or there will be a lot of junk characters printed after the string.


No comments:

Post a Comment