String operations are often used in the written examination and interview of companies of all sizes. The goal of the "string operation series" is to sort out common string operation questions and give the author's reference.Code. I will keep updating this series of blog posts, so stay tuned!
Question: Determine whether the specified sub-string exists in the string. If yes, the position of the first occurrence of the sub-string is returned. If no sub-string exists,-1 is returned. For example, the string is "abcdefghijk ", if the substring is "Ghi", 6 is returned. If the substring is "BDF",-1 is returned.
The C/C ++ language code is given below:
# Include <iostream> # include <assert. h> using namespace STD; int findsubstr (char * STR, char * sub) {assert (STR! = NULL & sub! = NULL); char * pstr = STR; char * psub = NULL; int Len = strlen (sub); While (* pstr! = NULL) {psub = sub; If (* pstr = * sub) {While (* psub = * pstr & * psub! = NULL) {pstr ++; psub ++;} // If * psub = NULL is compared, the sub-string exists and the index if (null = * psub) is returned) {return (pstr-str-len) ;}} else {pstr ++ ;}// if the substring does not exist, return-1 return-1;} int main () {char STR [] = "abcdefghijk"; char sub [] = "Ghi"; cout <findsubstr (STR, sub) <Endl; return 0 ;}
The running result is as follows: