【问题标题】:Comparing 2d string array to a string C++将二维字符串数组与字符串 C++ 进行比较
【发布时间】:2016-02-04 23:30:19
【问题描述】:

我有一个二维字符串数组和一个我想比较的字符串,但 strcmp 不起作用,除非我将字符串转换为 (const char*),这会导致我出现段错误。

目前我的代码简化为:

string dog;

cin >> dog;

string cat[10][10];

//The cat array is then filled with values through cin

//This is the troublesome part 

if (strcmp(cat[4][3].c_str(), dog[0]) == 0) {
//do stuff
}

使用 &dog[0] 获取 dog 的地址是可行的,但随后我得到了放入 dog 的整个单词,而不仅仅是我想要的字母。

有什么解决方法吗?

【问题讨论】:

  • 这里是some documentation。享受吧。
  • 如果只想比较第一个字符,则不需要strcmp。如果您想查看该单个字符是否在另一个字符串中的某个位置,请使用string::find

标签: c++ arrays string


【解决方案1】:

你正在使用 C++ std::string,它有一个重载的 operator==,所以你根本不需要 strcmp。如果你想看看两个strings 是否相等,你可以做cat[4][3] == dogcat[4][3]std::string,所以你可以直接和dog 比较。

如果你只是想比较第一个字符,你可以做cat[4][3][0] == dog[0]

【讨论】:

    【解决方案2】:

    字符串猫[10][10];

    //然后通过cin给cat数组填充值

    //这是比较麻烦的部分

    if (strcmp(cat[4][3].c_str(), dog[0]) == 0) {
    //do stuff
    }
    

    这就是我认为正在发生的事情。你想创建一个字符串 cat[10],而不是字符串 cat[10][10]

    现在让我解释一下。 //cat[0] = 这不需要“字符串”,它需要一个由 10 个字符串组成的数组[不是一个 10 个字符的字符串,我认为这是你所期望的)

    cat[0][0] = "hello world";
    //to access "h" letter you would need to use
    cat[0][0][0] and then do
    
    if (cat[0][0][0] != dog[0])
    

    我认为这是你想做的(比较一个字母),否则只是比较字符串

    if (cat[0][0] != dog) //note that this is a case sensitive
    

    【讨论】:

      最近更新 更多