简体   繁体   English

将子字符串复制到C中的字符串开头

[英]Copying a substring to the start of the string in C

I am trying to remove the whitespace at the start of a string, I have the index of the first non whitespace character, so I tried to do this: 我正在尝试删除字符串开头的空白,我具有第一个非空白字符的索引,因此我尝试执行以下操作:

int firstNonWhitespace = ...;
char *line = ...;
char *realStart = line + firstNonWhiteSpace;
strcpy(line, realStart);

but got Abort Trap 6 when at runtime. 但在运行时获得了Abort Trap 6。

However it works if I copy the realStart string to a temporary string, and then copy the temporary string to line: 但是,如果我将realStart字符串复制到临时字符串,然后将临时字符串复制到以下行,则该方法有效:

int firstNonWhitespace = ...;
char *line = ...;
char *realStart = line + firstNonWhiteSpace;
char *tstring = malloc(strlen(realStart) + 1);
strcpy(tstring, realStart);
strncpy(line, tstring, strlen(line));
free(tstring);

There are two problems with your code. 您的代码有两个问题。

  1. The source and destination in the call to strcpy() do overlap, which results in Undefined Behaviour. 调用strcpy()的源和目标确实重叠,这导致未定义的行为。

  2. It might well be the case that realStart points to some non-writeable area of memory. realStart可能指向某些不可写的内存区域。

The faster way is 更快的方法是

line += firstNonWhiteSpace;

but that might have consequences for your memory management, in case that part of memory was dynamically allocated. 但如果部分内存是动态分配的,那可能会对您的内存管理产生影响。 Only do this if you know what you are doing. 仅当您知道自己在做什么时才这样做。

int main()
{
    char a[] = "        hey";
    int i = 0;
    char *p = a;
    while(a[i++] == ' ');

    strcpy(p, p + i - 1);
    printf("%s\n", a);
}

Your problem is likely that you are not allowed to modify string literals, ie the code 您的问题很可能是您不允许修改字符串文字,即代码

int main() {
    int firstNonWhitespace = 3;
    char *line = "   foo";
    char *realStart = line + firstNonWhiteSpace;
    strcpy(line, realStart);
}

may or may not work depending on whether your platform protects against modifying the string literal " foo" . 取决于您的平台是否可以防止修改字符串文字" foo" ,它是否可以起作用。 Copying the string first is required by the language standard. 语言标准要求先复制字符串。

Also, since strcpy() is not guaranteed to work correctly on overlapping strings (you might get lucky, though), use memmove() to do the moving. 另外,由于不能保证strcpy()在重叠的字符串上正常工作(尽管您可能会很幸运),所以请使用memmove()进行移动。

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

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