[英]Repeatedly removing and replacing the occurence of a substring from the input string code is not working
[英]Repeatedly removing and replacing the occurence of a substring from the input string
我有這個作業問題:使用函數通過反復地將'foo'的每個出現替換為'oof',使用函數從輸入字符串中反復刪除子字符串foo的出現之后,編寫一個C程序來查找新字符串。
這是我的代碼:
#include <stdio.h>
#include <string.h>
void manipulate(char * a)
{
int i, flag = 0;
char newstr[100];
for (i = 0; a[i] != '\0'; i++) {
if (a[i] == 'f') {
if ((a[i + 1] != '\0') && (a[i + 1] == 'o')) {
if ((a[i + 2] != '\0') && (a[i + 2] == 'o')) {
i += 3;
flag++;
}
}
}
newstr[i] = a[i];
}
for (i = 0; i < flag; i++) {
strcat(newstr, "oof");
}
printf("\nThe output string is %s", newstr);
}
int main()
{
char a[100];
printf("Enter the input string");
scanf("%s",a);
manipulate(a);
return 0;
}
我認為我的代碼有問題,因為預期的輸出是:
Enter the input string
akhfoooo
The output string is akhoooof
但是我的實際輸出是:
Enter the input string
akhfoooo
The output string is akhoof
您能糾正我代碼中的錯誤嗎?
改變這個
scanf("%c",a);
對此
scanf("%s",a);
因為您想讀取字符串,而不是單個字符。
編輯以進行編輯(請參閱評論):
#include <stdio.h>
#include <string.h>
void manipulate(char * a)
{
int i = 0;
char *pch;
size_t len = strlen(a);
while(a[i]) // until we do not reach the null terminator
{
// so that we do not go after the end of the string
if(i + 2 == len)
break;
// if we found 'foo'
if(a[i] == 'f' && a[i + 1] == 'o' && a[i + 2])
{
// replace it with 'oof'
a[i] = 'o';a[i + 1] = 'o'; a[i + 2] = 'f';
i = i + 2; // and check for after the replacement we just made
}
// increment our counter to check the next charachter
i = i + 1;
}
printf("\nThe output string is %s\n", a);
}
int main()
{
char a[100];
printf("Enter the input string");
scanf("%s",a);
manipulate(a);
return 0;
}
如果要使用函數, strstr()會很好。
這樣就可以了。 注意邊界條件和何時退出。
#include <stdio.h>
#include <string.h>
void manipulate(char * a)
{
int i = 0;
char *pch;
size_t len = strlen(a);
while(a[i]) // until we do not reach the null terminator
{
// if we found 'foo'
if(a[i] == 'f' && a[i + 1] == 'o' && a[i + 2]=='o')
{
// replace it with 'oof'
a[i] = 'o';a[i + 1] = 'o'; a[i + 2] = 'f';
if ( i+3 == len){
break;
}
else{
i = i + 2; // and check for after the replacement we just made
continue;
}
}
else
{
i = i+1;
}
}
printf("\n\n\nThe output string is %s \n", a);
}
int main()
{
char a[100];
printf("Enter the input string \n");
scanf("%s",a);
manipulate(a);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.