Jump to content
  • Advertisement
Sign in to follow this  
peb

splitting strings... 2 questions

This topic is 5012 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites
Advertisement
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...

Share this post


Link to post
Share on other sites
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:


char str[] ="This is a sample string,just testing.";

char* args[32]; // <<< 32 is the max number of arguments you can store
int 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

Share this post


Link to post
Share on other sites
You could use std::vector to store what comes from strtok:


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!