web-dev-qa-db-ja.com

大文字と小文字を区別しない文字列比較C ++

文字列または1つを反復することを含むケース無視比較を行う方法があることを私は知っています 良いもの on SO別のライブラリが必要です。これを他のコンピュータに置く必要があります。インストールされていない可能性があります。これを行うために標準ライブラリを使用する方法はありますか?今私はただやっています...

if (foo == "Bar" || foo == "bar")
{
cout << "foo is bar" << endl;
}

else if (foo == "Stack Overflow" || foo == "stack Overflow" || foo == "Stack overflow" || foo == "etc.")
{
cout << "I am too lazy to do the whole thing..." << endl;
}

これにより、コードの可読性と使いやすさが大幅に向上する可能性があります。ここまで読んでくれてありがとう。

7
CoffeeRain

strncasecmp

strcasecmp()関数は、文字列s1s2のバイトごとの比較を実行します、文字の大文字と小文字を無視します。 s1がそれぞれより小さい、一致する、またはより大きいことが判明した場合、ゼロより小さい、等しい、またはより大きい整数を返します。 s2より。

strncasecmp()関数は、nバイトのs1以下を比較することを除いて、同様です。 およびs2.。

17
user405725

通常、私が行うことは、問題の文字列の小文字バージョンを比較することです。

if (foo.make_this_lowercase_somehow() == "stack overflow") {
  // be happy
}

ブーストには小文字の変換が組み込まれていると思います。

#include <boost/algorithm/string.hpp>    

if (boost::algorithm::to_lower(str) == "stack overflow") {
  //happy time
}
7
Greg Humphreys

すべてを小文字にして比較してみませんか?

tolower()

  int counter = 0;
  char str[]="HeLlO wOrLd.\n";
  char c;
  while (str[counter]) {
    c = str[counter];
    str[counter] = tolower(c);
    counter++;
  }

  printf("%s\n", str);
3
whtlnv

次のように、既存の文字列を小文字に変換する簡単な関数を作成できます。

#include <string>
#include <ctype.h>
#include <algorithm>
#include <iterator>
#include <iostream>

std::string make_lowercase( const std::string& in )
{
  std::string out;

  std::transform( in.begin(), in.end(), std::back_inserter( out ), ::tolower );
  return out;
}

int main()
{
  if( make_lowercase( "Hello, World!" ) == std::string( "hello, world!" ) ) {
    std::cout << "match found" << std::endl;
  }

  return 0;
}
2
Praetorian

私はこれを書いたばかりです、多分それは誰かに役立つかもしれません:

int charDiff(char c1, char c2)
{
    if ( tolower(c1) < tolower(c2) ) return -1;
    if ( tolower(c1) == tolower(c2) ) return 0;
    return 1;
}

int stringCompare(const string& str1, const string& str2)
{
    int diff = 0;
    int size = std::min(str1.size(), str2.size());
    for (size_t idx = 0; idx < size && diff == 0; ++idx)
    {
        diff += charDiff(str1[idx], str2[idx]);
    }
    if ( diff != 0 ) return diff;

    if ( str2.length() == str1.length() ) return 0;
    if ( str2.length() > str1.length() ) return 1;
    return -1;
}
2
davideanastasia