简体   繁体   English

更清洁的方法从C中删除str中的子字符串

[英]Cleaner way to remove a substring from str in C

I have the following string ID is a sample string remove to /0.10 , I would like to end up with the following: ID/0.10 . 我有以下字符串ID is a sample string remove to /0.10 ,我想最终得到以下内容: ID/0.10

This is what I came up with. 这就是我提出的。 However, I'm looking for a cleaner/nicer way of doing this. 但是,我正在寻找一种更清洁/更好的方法。

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] = "ID is a sample string remove to /0.10";
    char *a = strstr(str, "ID");
    char *b = strrchr (str, '/');
    if (a == NULL)
        return 0;
    if (b == NULL)
        return 0;

    int p1 = a-str+2;
    int p2 = b-str;
    int remL = p2 - p1;
    int until = (strlen(str) - p1 - remL) +1;

    memmove (str+p1, str+(p1+remL), until);
    printf ("%s\n",str);
    return 0;
}

After determining a and b you can simplify the memmove like this: 确定ab之后,您可以像这样简化memmove

char str[] = "ID is a sample string remove to /0.10";
char *a = strstr(str, "ID");
char *b = strrchr (str, '/');
if ((a == NULL) || (b == NULL) || (b < a))
    return 0;

memmove(a+2, b, strlen(b)+1);

The calculations you do on the string lengths are not really necessary. 你对字符串长度的计算并不是必需的。

#include <stdio.h>
#include <string.h>

int main ()
{
 char str[] = "ID is a sample string remove to /0.10";
 char *a = strstr(str, "ID");
 char *b = strrchr (str, '/');
 if (a == NULL || b == NULL)
    return 0;
 int dist = b - a; 
 if (dist <= 0) return 0;  // aware "/ ID"

 a += 2;
 while (*a ++ = *b ++);

 printf ("%s\n",str);

 return 0;
}

Or if you like a very dense version 或者如果你喜欢非常密集的版本

 char str[] = "ID is a sample string remove to /0.10";
 char *a = strstr(str, "ID");
 char *b = strrchr (str, '/');
 if (a == NULL || b < a) return 0; // no need to test b against NULL, implied with <
 a ++;
 while (*(++ a) = *b ++);

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

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