c - 字符串和字符的错误比较*

标签 c string string-comparison

我的程序从端口获取输入,然后我发送此字符串以检查几个字符串。我首先尝试比较,java 风格,只使用“myString”,但在比较时我得到了 13(十三)。我以为是因为我应该使用char指针,但我仍然得到13。然后我看到缓冲区以新行传递,所以我添加了\n但我得到了3(三)。从这里我不知道如何将它减少到 0。它必须是我传递字符串的方式。

获取字符串:

bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) 
    error("ERROR reading from socket");
printf("String at start: %s",buffer);
testingMethod(buffer);

测试方法是:
void testingMethod(char *string) {
    char *button = "mystring";
    printf("myString: %s-", string);
    printf("strcmp: %i", strcmp(myString,button));
...
}

输出:
String at start: mystring
string: mystring
-strcmp: 13 //NOTE the - on the nextline.

最佳答案

您的字符串中有一个剩余的换行符 ( '\n' )。你只需要删除它:

#include <string.h>

/* Gets a pointer to the last newline character in the string. */
char *pend=strrchr(string, '\n');

/* Avoids the undefined behavior by checking pend against NULL. */
if(pend!=NULL) *pend='\0';

关于c - 字符串和字符的错误比较*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313603/

相关文章:

c - 计算1 <= n <= 10000的三元组

c - 为什么我的 Makefile 每次都重新编译?

java - 从字符串中获取 2 个 double

python - 如果使用 pandas 一列超过 10 个字符,我如何删除整行

java - 用数字作为单词比较两个字符串

C:线程安全和操作顺序

c - 请求成员不是结构或 union 错误

javascript - 字符串到数字然后返回到 JavaScript 中的字符串加密/解密

arrays - Swift 字符串相等

objective-c - 检查对象实例的属性是否为 'blank'