32. Use of compare functions in C + +

Source: Internet
Author: User

The Compare function is used to compare strings and their substrings, as shown in the following example:

#include <iostream>#include<string>#include<cctype>usingstd::cout; usingStd::endl; usingstd::cin; usingSTD::string; intMainvoid){      stringstr1="Hi,test,hello"; stringStr2="hi,test"; //string comparison    if(Str1.compare (STR2) >0) printf ("str1>str2\n"); Else if(Str1.compare (STR2) <0) printf ("str1<str2\n"); Elseprintf ("str1==str2\n"); //str1 substring (starting at index 3, containing 4 characters) compared to str2    if(Str1.compare (3,4, str2) = =0) printf ("str1 the specified substring equals str2\n"); Elseprintf ("the specified substring of the str1 is not equal to str2\n"); //str1 Specifies that the substring is compared to the specified substring of the str2    if(Str1.compare (3,4, STR2,3,4)==0) printf ("the specified substring of the str1 equals the specified substring of str2 \ n"); Elseprintf ("the specified substring of the str1 is not equal to the specified substring of str2 \ n"); //str1 Specifies that substrings are compared to the first n characters of a string    if(Str1.compare (0,2,"Hi,hello",2)==0) printf ("STR1 a substring that is equal to the first 2 characters of the specified string \ n"); Elseprintf ("STR1 The specified substring is not equal to the first 2 characters of the specified string \ n"); return 0; }  

Execution Result:

32. Use of compare functions in C + +

Related Article

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.