我试图用C中的' '
(三下划线)替换'___'
(空格)。
这是我的代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *a = "12 34 56";
int a_l = strlen(a);
printf("str1: \"%s\" (%d)\n", a, a_l);
char *b = "___";
int b_l = strlen(b);
printf("str2: \"%s\" (%d)\n", b, b_l);
for (int i = 0; i < a_l; i++) {
if (a[i] == ' ') {
char *o = malloc(a_l + b_l);
strncpy(o, a, i);
strncpy(o + i, b, a_l);
//strncpy help
printf("out: \"%s\"\n", o);
}
}
return 0;
}
我认为到目前为止这是正确的,但是我需要用正确的
strncpy
替换注释行(取字符串a
的其余部分(不包括空格)并将其附加到字符串o
)。所以输出应该是这样的:str1: "12 34 56" (8)
str2: "___" (3)
out: "12___34 56"
out: "12 34___56"
如果我的代码中还有其他错误,请告诉我。
UPD:这不应该替换循环中的所有空格。如果源字符串包含8个空格,则应打印8行,并且每行中只应替换一个空格。
最佳答案
你太复杂了,所以我才说。
一些你肯定想阅读、学习、接受和使用的评论:
I.int
不适用于字符串长度和内容。size_t
用于字符串长度和内容。
二。字符串文本无法修改,因此使用传统的char *
类型将它们赋给变量无论如何都不好,const
限定了较差的指针基类型。
III.如果实际上不需要动态内存管理(我们不再生活在1989年),则使用VLAs而不是malloc()
。
IV.NUL
-终止字符串,因为C stdlib例程希望您这样做。
int main()
{
const char *in = "foo bar baz";
int nspc = 0;
for (const char *p = strchr(in, ' '); p; p = strchr(p + 1, ' '))
nspc++;
char buf[strlen(in) + nspc * 2 + 1];
memset(buf, 0, sizeof(buf));
const char *s = in;
for (const char *p = strchr(s, ' '); p; p = strchr(s, ' ')) {
strncat(buf, s, p - s);
strcat(buf, "___");
s = p + 1;
}
const char *end = in + strlen(in);
strncat(buf, s, end - s);
printf("%s\n", buf);
return 0;
}
关于c - 将字符串中的char替换为C中的另一个字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17394715/