【问题标题】:C++ string and char comparaison [duplicate]C ++字符串和字符比较[重复]
【发布时间】:2011-09-28 06:09:00
【问题描述】:

我有一个字符串"8120, 8120NGE, 8120NG, 8130, 8130NG, 8130NGE"

我有一个char* (0x0012d094 "8130")

我想看看“8130”是否在里面。那个确切的词。

所以我正在使用

  istringstream iss(boards);
  string token;
  AVBOOL foundBool=FALSE;
  while(std::getline(iss, token, ','))
  {
    const char * compareToken = token.c_str();  
    token.compare(board);     // with that : it doesn't work cause "8130" is not    equal   0x0012d094 "8130"
    if(strcmp(compareToken,board)==0) //with that it doesnt work cause 0x0012cef0 " 8130" is not equal 0x0012d094 "8130"
      {
        foundBool=TRUE;
      }
  }

所以问题是我如何将字符串与 char * 进行比较。

我是否需要将 char 转换为字符串然后使用 string.compare 要么 我需要将字符串转换为char并使用strcmp吗? 要么 我需要做点别的吗?

我有点迷路了。

【问题讨论】:

    标签: c++ string char


    【解决方案1】:

    boards.find( token )怎么样

    如果您需要它后面没有字母数字字符,只需检查是否有这样的

    如果是,则从该位置再次搜索

    干杯,

    【讨论】:

    • @Armen:呵呵,我编辑了答案,让你的评论看起来毫无意义:-)
    【解决方案2】:

    你可以同时使用。

    我更喜欢将 .c_str() 方法与 strcmp() C 函数一起使用,因为它不会创建字符串对象。

    【讨论】:

    • AFAIK, std::string 提供重载 bool operator==(const string&,const char*)bool operator==(const char*,const string&)token 已经是一个字符串。
    • 我不知道这些东西 :) !谢谢。
    【解决方案3】:

    使用std::set 会满足您的需求吗?

    std::set<std::string> boards;
    while (std::getline(iss, token, ',')) {
        boards.insert(token);
    }
    if (boards.find(board) != boards.end()) {
        // we found it
    }
    

    请注意,这并未考虑令牌中可能存在的空格。

    【讨论】:

      【解决方案4】:

      您的问题听起来好像您对比较感到困惑 - 您可以比较 stringconst char* 就好了!当包含的字符相等时,string::compare(const char*)strcmp 都将返回 0

      字符串一 = “pl”; 字符串二 = “前”; const char* too = "plex"; 主函数() { 字符串三 = 一 + 二; cout

      将打印

      0 0

      您的实际应用程序问题是您可能希望通过", " 拆分字符串,而标准库工具无法做到这一点。如果您通常无法摆脱 Mazurov 回答中提到的空格,您将需要一个接受字符串分隔符的标记器。

      【讨论】:

        【解决方案5】:

        我认为您需要重新编写代码,以便在读取标记之前去除空格。您可以这样调整循环:

        istringstream iss(boards);
        string token;
        bool found = false;
        while((iss >> std::ws) && std::getline(iss,token,','))
        {
            found |= (token == board);
        }
        

        循环也可以优化为在找到令牌时停止:

        while(!found && (iss >> std::ws) && std::getline(iss,token,','))
        {
            found = (token == board);
        }
        

        【讨论】:

          猜你喜欢
          • 2018-07-09
          • 1970-01-01
          • 2017-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多