【问题标题】:Compare String on C [duplicate]比较 C 上的字符串 [重复]
【发布时间】:2016-05-28 01:47:16
【问题描述】:

我写了这段代码,我想输入一个文本,比如"helloWorld",然后比较它,如果它与输入的文本匹配,那么它应该打印文本 101 次。但是,它不起作用,因为它似乎没有比较 if (string == "helloWorld") 中的字符串,它直接跳到 else 部分。请提供有关如何操作的必要详细信息。

这是我的代码:

#include<stdio.h>
#include<conio.h>

void main()

{
    int i;
    char string[30];
    clrscr();
    printf("Enter the string 'helloWorld' if you wanna see magic\n");
    scanf ("%s", string);
    printf("Your enterred Input is %s\n", string);
    if (string == "helloWorld")
    {
        for (i=0;i<=100;i++)
        {
            printf("%s\n",string);
        }
    }
    else
    {
        printf("Invalid Input\n");
    }
    getch();
}

另外,我知道在 C 中如果我们在 C 中使用 char variable[sting_length] 输入字符串,我们必须输入字符串没有任何空格。但是,有什么方法可以输入像“Hello World”这样的字符串,并且仍然可以完全打印/比较整个内容?

【问题讨论】:

  • 您无法将 C 字符串与 == 运算符进行比较。这将比较它们的地址,而不是它们的内容。查找标准的strcmp 函数。
  • “我们必须输入不带任何空格的字符串” - 嗯?如果“我们”是指你班上的人,这可能是你老师的限制。但对于其余部分,这是无稽之谈,C 标准没有强制要求。

标签: c string compare string-comparison


【解决方案1】:

为了读取带有空格的字符串,您可以创建一个循环读取字符直到它到达新行。

int i = 0;
char inputChar = ' ';
char* string = new char[STRING_SIZE];
do
{
     getch(inputChar);
     string[i] = inputChar;
     i++;
} while (inputChar != '\n' && i < STRING_SIZE);

在此代码中,STRING_SIZE 是您选择的任意大小的数组。

为了比较字符串,您必须检查每个元素以验证它们是否相同。

char compare[] = "Hello, world!";
int i = 0;
bool areEqual = true;
while (areEqual && compare[i] != '\n')
{
     if(compare[i] != string[i])
     {
         areEqual = false;
     }
}

使用这两段代码,您应该能够读取带有空格的字符串,然后将其与您选择的任何字符串进行比较。字符串也可能有不同的长度。

【讨论】:

  • getch 不是标准函数。还有更简单更好的方法。首先:使用标准函数,不要重新发明轮子!
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多