C++ 字符串比较的代码

作者:袖梨 2022-06-25

前面讲了可以利用 string 实例的 CompareTo 方法进行字符串比较,现在谈谈 string 的静

态方法 Compare,Compare 也是字符串比较,但功能更强。

基本语法

Compare 有多个重载函数,列出最简单的一个。

public static int Compare (
    string strA,
    string strB
)
返回值

小于零,strA 小于 strB;
零,strA 等于 strB;
大于零,strA 大于 strB。
示例

int result = string.Compare("abc", "ABC");
int result = string.Compare("abc", "ABC", true) //忽略大小写比较

但下面我们要讲的更复杂实用

#include
#include
using std::string;

main(void)
{
   string s1 = "abcdefghijk", s2 = "1234567890", s3,s4,s5;

   s3=s1+s2;
   cout << s3 <

   s4=s3;
   if (s4==s3)
      cout << " s4==s3 is truen";

   return(0);
}

/*
abcdefghijk1234567890
 s4==s3 is true

*/

进行字符大小比较

#include
using std::cout;
using std::endl;

#include
using std::string;

int main()
{
   string s1( "AA" );
   string s2( " AAB" );
   string s3;

   //
   cout << "s1 is "" << s1 << ""; s2 is "" << s2
      << ""; s3 is "" << s3 << '"'
      << "nnThe results of comparing s2 and s1:"
      << "ns2 == s1 yields " << ( s2 == s1 ? "true" : "false" )
      << "ns2 != s1 yields " << ( s2 != s1 ? "true" : "false" )
      << "ns2 >  s1 yields " << ( s2 > s1 ? "true" : "false" )
      << "ns2 <  s1 yields " << ( s2 < s1 ? "true" : "false" )
      << "ns2 >= s1 yields " << ( s2 >= s1 ? "true" : "false" )
      << "ns2 <= s1 yields " << ( s2 <= s1 ? "true" : "false" );
   return 0;
}

/*
s1 is "AA"; s2 is " AAB"; s3 is ""

The results of comparing s2 and s1:
s2 == s1 yields false
s2 != s1 yields true
s2 >  s1 yields false
s2 <  s1 yields true
s2 >= s1 yields false
s2 <= s1 yields true
 */

看实例

#include
using std::cout;
using std::endl;

#include
using std::string;

int main()
{
   string string1( "AAAAAAAAAAAAAA" );
   string string2( "BBBBBBBBBBBBBB" );
   string string3( "CCCCCCCCCCCCCC" );
   string string4( string2 );
  
   cout << "string1: " << string1 << "nstring2: " << string2
      << "nstring3: " << string3 << "nstring4: " << string4 << "nn";

   // comparing string2 and string4
   int result = string4.compare( 0, string2.length(), string2 );

   if ( result == 0 )
      cout << "string4.compare( 0, string2.length(), " << "string2 ) == 0" <<

endl;
   else {
      if ( result > 0 )
         cout << "string4.compare( 0, string2.length(), " << "string2 ) > 0" <<

endl;
      else
         cout << "string4.compare( 0, string2.length(), "
            << "string2 ) < 0" << endl;
   }
   return 0;
}

/*
string1: AAAAAAAAAAAAAA
string2: BBBBBBBBBBBBBB
string3: CCCCCCCCCCCCCC
string4: BBBBBBBBBBBBBB

string4.compare( 0, string2.length(), string2 ) == 0

 */

相关文章

精彩推荐