简体   繁体   English

比较字符串中的N个字节

[英]Comparing N bytes in string

I want to compare argv[1] and the string "pid", but I want to put restrict how much bytes to be compared. 我想比较argv [1]和字符串“ pid”,但是我想限制要比较的字节数。 I used strncmp, but there are problem, if I put on third argument 3 it compares more than 3 bytes. 我使用了strncmp,但是有问题,如果我输入第三个参数3,它将比较3个字节以上。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
    if (argc < 2)
        exit(EXIT_FAILURE);
    size_t i = 3;
    if (strncmp(argv[1], "pid", i) == 0){
        printf("%ld\n", (long)getpid());
    }

}

in the terminal 在终端

   $./main pid
   343
   $ ./main pidd
   354
   $ ./main piddd
   352

strncmp() compares three bytes in all of your three calls. strncmp()比较所有三个调用中的三个字节。 But because it only compares 3 bytes, you can't tell whether the argv[0] string ends after 3 characters or not. 但是因为它只比较3个字节,所以您无法确定argv[0]字符串是否以3个字符结尾。

If you want "pid" not to maych piddddd , try comparing 4 bytes, so that you hit the end-of-string marker ( '\\0' ). 如果您想让"pid"不增加piddddd ,请尝试比较4个字节,以便您击中字符串结尾标记( '\\0' )。

This might work: 这可能起作用:

int i,count=1;
char str[] = "pid";
    for (i = 0;i < 4;i++) 
   {
        if (str[i] != argv[1][i]) 
        {
            count = 0;
            break;
        }
    }
if(count==1)
  printf("%ld\n", (long)getpid());

You can have a check like this below: 您可以在下面进行如下检查:

if ((strlen(argv[1]) <= i) && strncmp(argv[1], "pid", i) == 0){

But for all three possible inputs you tried, the first 3bytes are "pid". 但是对于您尝试过的所有三个可能的输入,前3个字节均为“ pid”。 So strncmp will obviously returns 0 and is expected only. 因此,strncmp显然将返回0并且仅是预期值。

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

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