C++ 比较字符数组和字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1330550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:34:37  来源:igfitidea点击:

C++ Compare char array with string

c++stringstring-comparison

提问by Chris Klepeis

I'm trying to compare a character array against a string like so:

我正在尝试将字符数组与字符串进行比较,如下所示:

const char *var1 = " ";
var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).

这个if语句永远不会验证为真......当我输出var1时它是“dev”,我在想它可能与空终止字符串有关,但是“dev”和var1的strlen是相等的......我还认为 var1 == "dev" 正在将 "dev" 与 var1 的内存位置而不是值进行比较。*var1 == "dev" 导致错误.... 尝试了很多东西,可能是一个简单的解决方案,适用于 saavy c++ 开发人员(我很久没有编写 c++ 了)。

edit: we've tried

编辑:我们试过了

if(strcmp(var1, "dev") == 0)

and

if(strncmp(var1, "dev", 3) == 0)

Thanks

谢谢

edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.

编辑:在家测试后,我只是建议我的同事将数据类型更改为字符串。我相信他正在将一个大尺寸的 char 数组与一个字符串进行比较。我整理了一个输出 sizeof、strlen 等的程序来帮助我们解决它。感谢大家的帮助。

回答by John Millikin

Use strcmp()to compare the contents of strings:

使用strcmp()比较字符串的内容:

if (strcmp(var1, "dev") == 0) {
}

Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char*to a char*using the equality operator won't work as expected, because you are comparing the memory locationsof the strings rather than their byte contents. A function such as strcmp()will iterate through both strings, checking their bytes to see if they are equal. strcmp()will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.

解释:在 C 中,字符串是指向包含字节的内存位置的指针。使用相等运算符将achar*与 achar*进行比较不会按预期工作,因为您正在比较字符串的内存位置而不是它们的字节内容。诸如此类的函数strcmp()将遍历两个字符串,检查它们的字节以查看它们是否相等。strcmp()如果相等则返回 0,如果不同则返回非零值。有关更多详细信息,请参阅联机帮助页

回答by jalf

You're not working with strings. You're working with pointers. var1is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treatit as a string, but it is fundamentally just a pointer.

你不是在处理字符串。您正在使用指针。 var1是一个字符指针 ( const char*)。它不是一个字符串。如果是空值终止,那么一定C功能将对待它作为一个字符串,但它是从根本上只是一个指针。

So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).

因此,当您将它与 char 数组进行比较时,该数组也会衰减为一个指针,然后编译器会尝试找到一个operator == (const char*, const char*).

Such an operator does exist. It takes two pointers and returns trueif they point to the same address. So the compiler invokes that, and your code breaks.

这样的运营商确实存在。它需要两个指针,true如果它们指向同一个地址就返回。所以编译器调用它,你的代码就会中断。

IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.

如果要进行字符串比较,则必须告诉编译器您要处理字符串,而不是指针

The C way of doing this is to use the strcmpfunction:

这样做的 C 方法是使用strcmp函数:

strcmp(var1, "dev");

This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)

如果两个字符串相等,这将返回零。(如果左侧按字典顺序大于右侧,它将返回一个大于零的值,否则返回一个小于零的值。)

So to compare for equality you need to do one of these:

因此,要比较相等性,您需要执行以下操作之一:

if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}

However, C++ has a very useful stringclass. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:

但是,C++ 有一个非常有用的string类。如果我们使用它,您的代码会变得更简单一些。当然,我们可以从两个参数创建字符串,但我们只需要使用其中一个来创建字符串:

std::string var1 = getenv("myEnvVar");

if(var1 == "dev")
{
   // do stuff
}

Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.

现在编译器遇到字符串和字符指针之间的比较。它可以处理这种情况,因为字符指针可以隐式转换为字符串,从而产生字符串/字符串比较。这些行为完全符合您的预期。

回答by JaredPar

In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.

在此代码中,您不是在比较字符串值,而是在比较指针值。如果要比较字符串值,则需要使用字符串比较函数,例如 strcmp。

if ( 0 == strcmp(var1, "dev")) {
  ..
}

回答by sepp2k

"dev" is not a stringit is a const char *like var1. Thus you are indeed comparing the memory adresses. Being that var1is a char pointer, *var1is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.

“dev”不是 astring它是一个const char *like var1。因此,您确实在比较内存地址。因为它var1是一个字符指针,所以*var1是一个单独的字符(准确地说是指向字符序列的第一个字符)。您不能将 char 与 char 指针进行比较,这就是为什么它不起作用。

Being that this is tagged as c++, it would be sensible to use std::stringinstead of char pointers, which would make == work as expected. (You would just need to do const std::string var1instead of const char *var1.

因为这被标记为 c++,所以使用std::string而不是 char 指针是明智的,这将使 == 按预期工作。(您只需要执行const std::string var1而不是const char *var1.

回答by AraneaSerket6848

There is more stable function, also gets rid of string folding.

有更稳定的功能,也摆脱了字符串折叠。

// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
    /*
     * This function wraps string comparison with string pointers
     * (and also works around 'string folding', as I said).
     * Converts pointers to std::string
     * for make use of string equality operator (==).
     * Parameters use 'const' for prevent possible object corruption.
     */
    std::string var0 = (std::string) arg0;
    std::string var1 = (std::string) arg1;
    if (var0 == var1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

And add declaration to header

并在标题中添加声明

// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);

For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.

对于用法,只需放置一个 'string_equal' 调用作为 if(或三元)语句/块的条件。

if (string_equal (var1, "dev"))
{
    // It is equal, do what needed here.
}
else
{
    // It is not equal, do what needed here (optional).
}

Source: sinatramultimedia/fl32 codec (it's written by myself)

来源:sinatramultimedia/fl32 codec(我自己写的)

回答by 101dolmations

your thinking about this program below

你对下面这个程序的想法

#include <stdio.h>
#include <string.h>

int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
  printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6

when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below

当您应该考虑将某些内容输入数组然后使用 strcmp 函数(如上面的程序)时……查看下面的修改后的程序

#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;

int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];

for(int j=0; j<=Projects-1; j++){
  for(int i=0; i<=Students; i++) {
 cout <<"Please give grade of student "<< j <<"in project "<< i  <<  ":";
  cin >> Grades[j][i];

  }
  Sum2 = Sum2 + Grades[i][j];
     Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is  : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}

change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers

更改为字符串,除了它只读取 1 个输入并抛出其余的可能需要两个 for 循环和两个指针

#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;

char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}   
int length = 0;
while(name[length] != '##代码##')
{
length++;
}
                    for(n=0; n<4; n++)
                {
                            if (strncmp(ptr, "snit", 4) == 0)
                            {
            cout << "you found the snitch "    <<        ptr[i];
                            }
                }
cout<<name <<"is"<<length<<"chars long";
}