Whether the specified sub-string exists in the string Operator Series _ 3 string

Source: Internet
Author: User

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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.