【问题标题】:How to compare string without using strcmp and square brackets?如何在不使用 strcmp 和方括号的情况下比较字符串?
【发布时间】:2016-02-11 01:40:55
【问题描述】:

例如,我有一个结构数组,其中包含很多名称,并且我有一个指向该结构的指针。而且我有一个输入让用户输入名称以匹配结构中的名称我应该怎么做而不使用字符串并且只使用指针?

struct people{
   char name[20];
}

people list[10];
people *ptr;
ptr = list;
char lists[20];
char *inpu;
inpu = lists;

cout << "Input name";
cin >> inpu;

我试过用这个,但效果不好。

If ( inpu == (*ptr).name){
       cout << "1";
}
else cout << "2";

【问题讨论】:

  • 不,即使它们具有相同的文本,它们也不是相同的字符串,因此也不是相同的指针。
  • 是的,我尝试计算输入名称和结构名称指针指向的结果,它们显示相同,但​​它从来没有 cout 1。我该如何纠正它?你能帮我吗
  • 我想尝试用指针解决它的另一种方法
  • @Hong 所以继续 - 去做吧。制定限制并要求其他人完成有什么意义?
  • 使用关系运算符将字符数组转换为std::string比较。

标签: c++ c pointers struct


【解决方案1】:

如果你不想使用 strcmp,请使用 here 中的完全notstrcmp:

int totallynotstrcmp(const char* s1, const char* s2)
{
    while(*s1 && (*s1==*s2))
        s1++,s2++;
    return *(const unsigned char*)s1-*(const unsigned char*)s2;
}

【讨论】:

  • (unsigned char)*s1 - (unsigned char)*s2 会更短更容易阅读
  • 迂腐:(*(const unsigned char*)s1 &gt; *(const unsigned char*)s2) - (*(const unsigned char*)s1 &lt; *(const unsigned char*)s2); 不会溢出。处理具有相同范围的罕见unsigned char, unsigned
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 2019-06-19
  • 1970-01-01
  • 2018-02-24
相关资源
最近更新 更多