Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Get first occurence in a string from characters in a second string in C

Published on Saturday, 21st August 2010.

K&R's Exercise 2-5 looked easy enough, so I gave it a shot and came up with this little beauty.

int any(const char str1[], const char str2[]) { int i = 0; while (str1[i] != '\0') { int j = 0; while (str2[j] != '\0') { if (str1[i] == str2[j]) { return i; } ++j; } ++i; } return -1; }
Write the function any(s1,s2), which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location.)

Comments

No comments yet.

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »