简体   繁体   English

C strcmp中的字符串比较

[英]String Comparison in C strcmp

I have domain names stored in a 2 dimensional array of char 我的域名存储在char的二维数组中

char domainNames[2][4096]= {"www.yahoo.com","java.sun.com"};

and I need to check if a given domain name stored in another array( char data[4096]; ) exists in the list, if the domain name is found, store all the IP addresses found in char IP[2][4096]= {"87.248.122.122","192.9.162.55"}; 并且我需要检查列表中是否存在存储在另一个数组( char data[4096]; )中的给定域名,如果找到该域名,则将在char IP[2][4096]= {"87.248.122.122","192.9.162.55"}; separated by "#" in the array char msg[4096]; char msg[4096];数组中用“#”分隔char msg[4096];

this is the way I did it: 这是我做到的方式:

  for (i=0; i< 2;i++)
  {
    if(strcmp(domainNames[i], data)==0)
    {
      strcat(msg, IP[i]);
      strcat(msg, "#");
      found = true;
    }
  }

  if(!found)
    strcpy(msg,"IP not found");

  break;
}

The problem is that the result is always "IP not found" even if the string does exist. 问题是即使字符串确实存在,结果也总是“找不到IP”。

Since you have a problem with newline characters being left on the input, you can just apply a simple check for the newline character and remove it if present: 由于在输入中留下了换行符,因此您可以对换行符进行简单的检查并将其删除(如果存在):

size_t ln = strlen(data) - 1;
if ((ln > 0) && (data[ln] == '\n'))
    data[ln] = '\0';
for (i=0; i< 2;i++)
{
  if(strcmp(domainNames[i], data)==0)
  {
    strcat(msg, IP[i]);
    strcat(msg, "#");
    found = true;
  }

Because you're getting your input ( data ) from an external source, it would probably serve you well to thoroughly verify this prior to doing anything with it. 由于您是从外部来源获取输入( data ),因此在进行任何操作之前,最好先对其进行彻底验证。 Make a new function and pass data to it, verify you've stripped newlines, make sure there are no white space characters, make sure it ends with ".com" or whatever... anything that comes from an external source should be validated to the best of your ability before using it, not only to help with debugging, but also to avoid attacks (intentional or not). 创建一个新函数并向其传递数据,验证是否已去除换行符,确保没有空格字符,确保其以".com"或任何其他结尾...应当验证来自外部来源的任何内容在使用它之前,请尽您最大的能力,不仅可以帮助调试,还可以避免攻击(有意或无意)。

Also, just a slight (possible) optimization for you, if msg is empty prior to this function, you can always just check for a 0 length and remove the extra found Boolean that way. 此外,只为你一个轻微的(可能)的优化,如果msg是此功能之前,空的,你总是可以只检查一个0长度和删除多余的found布尔的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM