4

我有以下字符串ID is a sample string remove to /0.10,我想得到以下结果:ID/0.10

这就是我想出的。但是,我正在寻找一种更清洁/更好的方式来做到这一点。

#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;
}
4

2 回答 2

3

确定后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);

您对字符串长度所做的计算并不是真正必要的。

于 2012-06-03T15:34:40.303 回答
1
#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;
}

或者,如果您喜欢非常密集的版本

 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 ++);
于 2012-06-03T15:35:19.293 回答