I was going to post this as a challenge, but i thought its probably be a little easy, and maybe to boring to do.
But none the less its a pretty neat function. I'm sure C/C++ has similar functions, but i like writing my own.
if any have ideas on how to make it better id like to hear them.
oh yeah, the function returns a int telling you the position of a string n in a string h, if its not a substring it return -1
// findString returs the possition of a substring n "needle" if it exsists is h "haystack", returns -1 if non found.
int findSTR(char *n, char *h)
{
int p1 = 0;
int p2 = 0;
while(h[p1] != NULL)
{
p2 = 0;
while(n[p2] == h[p1+p2])
{
p2++;
if(n[p2] == NULL)
return p1;
if(h[p1+p2] == NULL)
return -1;
}
p1++;
}
return -1;
}
[/b]
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
#include <string.h>
//...
char* str1 = "this is a string of characters";
char* str2 = "a string";
char* result = strstr( str1, str2 );
if( result == NULL ) printf( "Could not find '%s' in '%s'\n", str2, str1 );
else printf( "Found a substring: '%s'\n", result );
When run, the above code displays this output:
Found a substring: 'a string of characters'
yeah, the reason i put this down was because it would help on my next challange, but i think it was a bit optimistic.
i wanted to make a challenge where you could do a search like this but use regular expressions.
int find(char *n, char *h) then having you n be something like '[0-9][*][0-9]' so return if a string started with a number and ended with a n umber, but i dont thing that will be the challenge. its a little boring, however, if you wanna have a leg up on someone in the industry teach yourself how to use regular expressions in your programs.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Here's an adaption of your code with basically the same functionality, except that it doesn't include the 2nd if statement and returns a char * instead of an index.
Amarant wrote:Here's an adaption of your code with basically the same functionality, except that it doesn't include the 2nd if statement and returns a char * instead of an index.
Amarant wrote:True, and that's why I said it had 'basically' the same functionality and not 'exactly' the same functionality.
yeah. but i do like your code. its elegant.
hey, have you looked at the new challenge, its number 4. its a very nice challenge. its hard. but ive you oppertunity to wrote beautiful code.
im almost finished.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
This probably would have been useful to know about 2 days ago when i had to write a program to solve random complex infix, postfix, and prefix math problems...XD
Meh, you learn new shit every day.
Edit: not imaginary numbers. XD multi-operational.
<qpHalcy0n> decided to paint the office, now i'm high and my hands hurt