Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Find in C

Tags:

c

string

What I need to do is find what position a certain string is at, and only keep what's after that.

Pseudo-code:

string1 = "CDSDC::walrus"
string2 = "::"
string3 = (substr( string1, strfind(string1, string2) + 2 )) // +2 being the len of str2
// at this point I want string3 == "walrus"
like image 450
W00t Avatar asked Jun 01 '12 04:06

W00t


1 Answers

strstr does what you want. ie locate substrings.

const char * strstr ( const char * str1, const char * str2 );

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

For your example,

char *string3 = strstr(string1,"walrus")

Or, if you want to split strings into tokens based on delimiters like :: use can use strtok

char * strtok ( char * str, const char * delimiters );

Split string into tokens

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

For your example,

strtok(string1, "::");
string3 = strtok(NULL,"::")

strtok is a tricky function in the sense that it modifies the string you are tokenizing and is also not re-rentrant. Here is a nice article explaining the overall aspects of using strtok

like image 158
Pavan Manjunath Avatar answered Sep 29 '22 13:09

Pavan Manjunath