我正在创建一个名为removeString()
的函数。它的目的是从文本中删除一个字符串
示例:如果文本是“错误的儿子”并且我想删除“错误”为“儿子”,我使用此功能。
原型是:
void removeString(char source[], int start, int numofchrem);
,程序是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void removeString(char source[], int start, int numofchrem)
{
int i, j, k;
char n[20];
j = start + numofchrem - 1;
for (i = 0; i < numofchrem; i++)
{
if (source[start] == '\0')
break;
source[j] = '\b';
j--;
}
printf("%s", source);
}
int main()
{
char text[] = "the wrong son";
void removeString(char source[], int start, int numofchrem);
removeString(text, 4, 6);
}
当我编写程序时,我首先调试了源代码中的字符,就像这样
"the \b\b\b\b\b\bson"
当我使用以下内容在源内打印文本时:
printf("%s",source);
节目只显示“儿子”而不是“儿子”。所以,如果有人能帮助我,我会非常感激。
答案 0 :(得分:1)
您需要将"son"
(以及'\0'
)移回您想要替换的内容
void removeString(char source[], int start, int numofchrem)
{
char *d = source + start; // d points to "wrong..."
char *s = source + start + numofchrem; // s points to "son"
while (*s != '\0') {
*d = *s; // replace 'w' with 's', 'r' with 'o', ...
d++; // point to next: "rong...", "ong...", "ng..."
s++; // point to next: "on", "n"
}
*d = '\0'; // terminate string
}