简体   繁体   English

比较两个字符串在C ++问题。

[英]Comparing two strings in c++ issue.

Having this code: 具有以下代码:

char a[20]="wasd", b[20]="asd";
if((a+1)==b)
    printf("yes");

Will not return "yes", even if "a+1" is "asd". 即使“ a + 1”是“ asd”,也不会返回“是”。 I am wondering what am I doing wrong? 我想知道我在做什么错?

You need to use strcmp to compare C strings. 您需要使用strcmp比较C字符串。 == will just compare the pointers. ==将只比较指针。

For example: 例如:

#include <string.h> // or <cstring> if you're writing C++
...
char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b)==0)
    printf("yes");

By the way, if you're writing C++, you'd be better off using std::string . 顺便说一句,如果您正在编写C ++,则最好使用std::string Then you could have simply used == to compare them. 然后,您可以简单地使用==进行比较。

If it's not a student assignment and you truly are using C++(as your tag says) you should use strings . 如果不是学生作业,而您确实使用的是C ++(如标签所示),则应使用strings Now you're using arrays and comparing arrays addresses instead of real strings. 现在,您正在使用数组并比较数组地址而不是实际字符串。 In a C++ way your code might look like: 以C ++方式,您的代码可能类似于:

#include <iostream>
#include <string>

int main()
{
    std::string a ="wasd";
    std::string b ="asd";
    if(a.substr(1) == b)
        std::cout << "Yes!\n";
}

Well, there is a better way to find if one string contains another but the code is a direct mapping of your C code to the C++-ish one. 好了,有一种更好的方法来查找一个字符串是否包含另一个字符串,但是代码是将您的C代码直接映射到C ++类的字符串。

You are actually comparing pointer addresses, not the actual string contents. 您实际上是在比较指针地址,而不是实际的字符串内容。

Your code should use strcmp : 您的代码应使用strcmp

char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b) == 0)
    printf("yes");

Be careful that strcmp returns 0 if the strings are identical. 请注意,如果字符串相同,则strcmp返回0。

A better and more idiomatic alternative would be to use std::string : 更好,更惯用的替代方法是使用std::string

std::string a = "wasd", b = "asd";
if(a.substr(1) == b)
    std::cout << "yes";

substr does copy the string though, so it is slightly less efficient than the previous approach. 尽管substr确实复制了字符串,所以它的效率比以前的方法略低。

You have to use strcmp from string.h to compare strings. 您必须使用string.h中的strcmp来比较字符串。 if(strcmp(a+1,b)==0) in Your case. if(strcmp(a+1,b)==0)在您的情况下。

As per your code, when using (a+1)==b you are comparing the addresses of the pointers pointing respectively to second character of string 'a' and the first character of string 'b'. 根据您的代码,当使用(a + 1)== b时,您正在比较分别指向字符串'a'的第二个字符和字符串'b'的第一个字符的指针的地址。

It can work if you modify your code as: 如果将代码修改为:

char a[20]="wasd", b[20]="asd";
if(*(a+1)==*b)         // now we are comparing the values towards which the
    printf("yes");     // respective pointers are pointing

You can also use compare() for comparison of strings included in . 您也可以使用compare()来比较中包含的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM