string function

I have a question concerning string functions. I have not been able to locate a function that does what I want, so I fugured I'd ask before I wrote on myself.
Is there a function to which I can pass 2 strings (character string a and character string b) and have it tell me if string b appears anywhere in string a?

ie, can it determine if "test" exists in the string "this is a test"?

grep will do what you want. If you just want a "yes it exists" or "no it doesn't" answer, just check $? after you have done the grep. This example might help :

stringa=test
stringb="this is a test"
echo $stringb | grep $stringa >> /dev/null
if [ $? = 0 ]
then
echo "Match Found"
else
echo "No Match Found"
fi

TioTony

I assume the original poster choose to post on the C programming forum, he/she may want an answer with the C programming language, not shell script.

Try the strstr() function.

From the man page of string.h functions:

#include <string.h>

char *strstr(const char *s1, const char *s2);

strstr()
The strstr() function locates the first occurrence of the
string s2 (excluding the terminating null character) in
string s1 and returns a pointer to the located string, or a
null pointer if the string is not found. If s2 points to a
string with zero length (that is, the string ""), the func-
tion returns s1.

int CheckSubStr( char * MainStr , char * SearchStr )
{
int StartIndex,Index, Counter ;
for (StartIndex=strlen(MainStr)-strlen( SearchStr ) ; StartIndex >= 0 ; StartIndex --)
for ( Index = 0 , Counter = StartIndex ; Index < strlen ( SearchStr ) && MainStr[Counter++]==SearchStr[Index++]; )
if ( SearchStr [Index] == '\0' )
return 0 ; /* Matched /
return 1 ; /
Not Matched */
}

Yes, I was looking for a C function. Thanks, cbkihong. It looks like strstr() was exactly what I was looking for. :smiley:

Sorry, I had Shell scripting on the brain and didn't notice you posted in the C forum.

Actually I am after a C shell scripting solution myself.

Can you use the C functions of Unix, especially the string functions, within a C shell? How?

Thanks

No you cannot use C functions in the shell, unless you write C code to do it and then call it from the shell.

try man awk

awk has functions like substr, index. Plus printing variables with a space between them conctenates.

Most shells have good ways of handling strings, but most times they are not eexplicit functions like you have in either awk or C.