C ++比较char数组与字符串 [英] C++ Compare char array with string

查看:1073
本文介绍了C ++比较char数组与字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较一个字符数组与一个字符串,如下:

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

if(var1 ==dev)
{
// do stuff
}
$ p>

这个if语句从不验证为true ...当我输出var1它是dev,我想或许它有一些与终止的字符串有关,但是dev和var1的strlen是相等的...我也认为可能var1 ==dev比较dev与var1的内存位置,而不是值。 * var1 ==dev会导致错误....尝试了很多东西,可能是一个简单的解决方案为saavy c ++开发人员(我havent编码c ++在一个悠闲的时间)。



编辑:
我们尝试了

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

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

谢谢



编辑:在家里测试后,我只是建议我的同事更改数据类型为字符串。我相信他正在比较一个大型字符数组对一个字符串。我把一个程序,输出sizeof,strlen等,以帮助我们通过它。感谢大家的帮助。

解决方案

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

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

说明:在C中,字符串是指向包含字节的内存位置的指针。使用等于运算符将 char * 比较到 char * 将无法正常工作,因为您正在比较字符串的内存位置,而不是它们的字节内容。例如 strcmp()的函数将遍历这两个字符串,检查它们的字节,看它们是否相等。 如果strcmp()相等,则返回0;如果它们不同,则返回非零值。有关详情,请参见手册页


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).

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.

解决方案

Use strcmp() to compare the contents of strings:

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 locations of 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 ++比较char数组与字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆