【问题标题】:Cleaner way to remove a substring from str in C从 C 中的 str 中删除子字符串的更简洁方法
【发布时间】:2012-06-07 22:47:32
【问题描述】:

我有以下字符串 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;
}

【问题讨论】:

  • 正是我想要的。谢谢!

标签: c string substring memmove


【解决方案1】:

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

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

【讨论】:

  • 这个版本的长度计算过多。
  • 请修正memmove()末尾多余的括号。
【解决方案2】:
#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 ++);

【讨论】:

  • 你确定while (*a ++ = *b ++);的行为是由C标准定义的吗?
  • 我很确定使用该片段的 strcpy 的早期实现。你在哪里看到问题? (好的,你必须忽略警告)(另见stackoverflow.com/questions/7962159/…
  • 没有空格,其实就是K&R strcpy():while (*a++ = *b++);.
  • @stefanbachert,好像没问题。
猜你喜欢
  • 2014-04-02
  • 2015-04-11
  • 2016-09-12
  • 1970-01-01
  • 2021-08-13
  • 2021-10-16
  • 2022-01-06
相关资源
最近更新 更多