splitting strings... 2 questions
Hello there.. How are you all doing?
Anyways, i need a function for splitting strings... ex:
this is my string: "hello world!. this sux!"
so arg[0] will be hello
arg[1]: world!.
arg[2]: this
arg[3]: sux!
get it?
okay question number two:
how can i get rid of individual characters in a string?
i have this: ":::::hello" and i want it to be "hello"
thank you..
best regards, max
EDIT: auch, forgot two things: im running linux, and im programming in C... Than kyou :)
strtok() may be what you are looking for, though, I am sure there are better options for what you want.
Actually i just tested that:
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a sample string,just testing.";
char * pch;
printf ("Splitting string \"%s\" in tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.");
}
return 0;
}
But how can i add code to that so it makes args[0] is "this" args[1] is "is" and so on...
couse i dont know how i could use that otherwise
thanks...
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a sample string,just testing.";
char * pch;
printf ("Splitting string \"%s\" in tokens:\n",str);
pch = strtok (str," ");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.");
}
return 0;
}
But how can i add code to that so it makes args[0] is "this" args[1] is "is" and so on...
couse i dont know how i could use that otherwise
thanks...
Here's a way of doing it but there is one drawback - there is a maximum number of arguments that you can store. You could always go through the string first and count the number of delimitting characters - from this you could work out a safe size for your 'args' array. Or, you could do something with dynamic memory like a linked list...
Anyway, here's the code:
At the end of the loop, 'iNumArgs' would store the total number of arguments in the string and the 'args' array would hold the pointers to your arguments...
James Bird
Anyway, here's the code:
char str[] ="This is a sample string,just testing."; char* args[32]; // <<< 32 is the max number of arguments you can storeint iNumArgs = 0; args[0] = strtok(str, " ");while ( args[iNumArgs] ){ args[++iNumArgs] = strtok( NULL, " ,." );}
At the end of the loop, 'iNumArgs' would store the total number of arguments in the string and the 'args' array would hold the pointers to your arguments...
James Bird
You could use std::vector to store what comes from strtok:
That should work
char str[] ="This is a sample string,just testing."; std::vector<char*> args;int iNumArgs = 0; args[0] = strtok(str, " ");while ( args[iNumArgs] ){ args.push_back(strtok( NULL, " ,." )); iNumArgs++;}
That should work
Only problem with using std::vector is that it does not exist in C.
Minor technicality. =)
Chris
Minor technicality. =)
Chris
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement