如何在C比较字符串的条件 [英] How to compare strings in C for a condition

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

问题描述

我在用C比较两个字符串的麻烦,看看他们是平等的。

I'm having trouble comparing two strings in C to see if they are equal.

switch(i) {
case 1:
  printf("Got in case 1.  TextA=%s    word=%s \n",TextA,word);
  if(TextA == word) {       
    SubTypeOption = 1;
    printf("SubTypeOptioon = %d",SubTypeOption);
  }

在我的输出,我得到了的情况下,1 TEXTA = SupTypeA字= SupTypeA
                     SubTypeOption = 0//所以它不以某种方式修改

On my output, i get "Got in case 1. TextA=SupTypeA word=SupTypeA SubTypeOption = 0" //So it wasn't changed somehow

推荐答案

== 运算符比较的指针的。它成功只有当两个的char * 指向同一个地址在内存中。比较字符串'的内容的在C需要 STRCMP的呼叫 或<一个href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/strncmp.html\"><$c$c>strncmp:

The == operator compares pointers. It succeeds only when the two char* point to the same address in memory. Comparing strings' content in C requires a call of strcmp or strncmp:

if (strcmp(TextA, word) == 0) {
    // Strings are identical
}

请注意比较为零:这是必需的,因为 STRCMP 功能比较字符串的字典序<​​/ em>的,返回时零字符串相等。您需要包括&LT; strings.h方式&gt; 为了使用 STRCMP

Note the comparison to zero: it is required because strcmp functions compare strings lexicographically, returning zero when the strings are equal. You need to include <strings.h> in order to use strcmp.

这篇关于如何在C比较字符串的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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