簡體   English   中英

C ++中的字符串比較如何工作?

[英]How does strings comparison in C++ work?

我正在努力解決這個問題

我正在用字符串實現它。 這是我的代碼片段

string s,ss;
// s and ss both contains integer input.

while(s <= ss )
//while( s<=ss && s.size() <= ss.size())
{
    int i = inc, j = dec;   // inc and dec are middle values. both equal if odd else different

    while((s[j]-'0')==9 && i < len && j>=0){
        // for cases like 999
        s[i] = s[j] = '0';
        i++;
        j--;
    }
    if(j<0){
        s = "1" + s;
        int l = s[len-1] - '0';
        l++;
        //cout<<l<<"\n";
        s[len] = (l + '0');
    }
    else{
        int l = s[j] - '0';
        l++;
        s[i] = s[j] = (l+'0');
    }

    if(s <= ss)
        cout<<"out in wild "<<s<<" and "<<ss<<"\n";
}

cout<<s<<endl;

我面臨的問題是輸入類似999或9999時。即使s的值增加,外部的while循環也會繼續循環,但是如果我加上while( s<=ss && s.size() <= ss.size())完全正常。 為什么while(s <= ss)不起作用? 我很少使用string類,因此我不太了解它。 為什么不讓string s= 101ss=99停止while循環?

完整的代碼鏈接在這里

您要比較的是按字典順序而不是數字的字符串,因此“ 101”小於“ 99”(因為'1'<'9'),例如

int main(){
    std::string s = "99";
    std::string ss = "101";

    std::cout << std::boolalpha << (s <= ss);  
}

輸出false

筆記:

  • 程序的更好設計是首先處理數字( intdouble ...),而不要處理字符串,因此,這種表達式自然可以按您期望的那樣工作。

    例如,“ 101” +“ 99”是“ 10199”,而不是“ 200” ...

  • 但是,如果您確實需要字符串,請考慮這篇文章以對包含數字的字符串進行排序。

  • 如@Deduplicator所指出的,不必要地過度使用字符串的程序有時稱為Stringly Typed

  • 另請參見std::lexicographical_compare


由於您的輸入明確只包含不帶前導0的正整數 ,因此編寫比較函數很簡單,例如:(unested)

/* Returns 1 if the integer represented by s1 > the integer represented by s2
*  Returns -1 if the integer represented by s1 < the integer represented by s2
*  Return 0 is both are equals
*
*  s1 and s2 must be strings representing positive integers without trailing 0
*/
int compare(const std::string& s1, const std::string& s2)
{
  if(s1.size() > s2.size())
      return 1;
  if(s2.size() > s1.size())
      return -1;

  for(std::size_t i = 0 ; i < s1.size() ; ++i)
  {
    if(s1[i] - '0' < s2[i] - '0')
      return 1;
    if(s2[i] - '0' < s1[i] - '0')
      return -1;
  }

  return 0;
}

盡管sss是字符串變量,但將它們逐個字符地進行比較。

如果您提到的是: s = "101"ss = "99" ,則第一手將檢查每個字符串中的第一個字符,並且當'1' < '9'時以s < ss退出。 我建議您在比較之前將這些值轉換為整數。

由於按字母順序將s與ss進行比較,我建議您將尾部的一個字符與頭部的一個字符進行比較(一個到一個地到達中間),以解決該問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM