[英]removing substring from main string with c
I need to remove substring "hello"
from the mains string and now I have already replaced 'x'
with 'ks'
and 'z'
with 'ts'
as my assignment asked my to do.我需要从主字符串中删除子字符串
"hello"
,现在我已经按照我的作业要求将'x'
替换为'ks'
,将'z'
替换为'ts'
。 But now I can't think of a way to remove substrings "hello"
and I've tried that with memmove()
but after that the printf prints "(null)"
.但是现在我想不出删除子字符串
"hello"
,我已经用memmove()
尝试过,但之后 printf 打印"(null)"
。
My code:我的代码:
#include <stdio.h>
#include <string.h>
void antikorso(char *dest, const char *src) {
const char *p = src;
int i;
for (i = 0; *p != '\0'; i++, p++)
{
if (*p == 'x') {
dest[i++] = 'k';
dest[i] = 's';
}
else if (*p == 'z') {
dest[i++] = 't';
dest[i] = 's';
}
else
{
dest[i] = *p;
}
}
dest[i] = '\0';
printf("\n%s", dest);
char c[10] = "hello";
int j;
while (dest = strstr(dest, c))
memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));
printf("\n%s", dest);
}
int main(void)
{
const char *lol = "yxi izexeen hello asd hello asd";
char asd[1000];
antikorso(asd, lol);
}
Just a logic error on your side.只是你这边的逻辑错误。 It prints
NULL
because after you've removed "hello"
, the condition in the while
loop gets evaluated again and this leads to:它打印
NULL
因为在您删除"hello"
, while
循环中的条件将再次评估,这导致:
dest = strstr(dest, c);
which eventually will assign NULL
to dest
, which is what you print.最终会将
NULL
分配给dest
,这就是您打印的内容。 You need another variable to remember the original string.您需要另一个变量来记住原始字符串。
char *original = dest;
char c[10] = "hello";
while (dest = strstr(dest, c))
memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));
printf("\n%s", original);
This will print you line without "hello"
s.这将打印没有
"hello"
的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.