我试图向用户询问 3 个不同的字符串,如果第二个字符串是第一个字符串的一部分,它将用第三个字符串替换该部分。除此之外,我必须使用指针算法来索引任何数组/字符串。例如:
string1 = foobar
string2 = oba
string3 = 12345
output = fo12345r
当模式字符串(string2)和替换字符串(string3)的长度相同时,我的程序可以工作,但如果不是,我会得到奇怪的结果。
例如:
s1: foobar
s2: obar
s3: 3333
r: fo3333
(^作品)
s1: foobar
s2: obar
s3: 33
r: fo33 ends without including the original last 2 characters ('a','r')
(^不起作用)
s1: foobar
s2: obar
s3: 12345
r: fo1234 ends without including the last new character ('5')
(^不起作用)
#include <stdio.h>
void GetString(char *str);
void StringReplace(char *original, char *pattern, char *replacement);
int main(void){
char originalstring[256];
char patternstring[32];
char replacement[32];
printf("Please enter the original string:\n");
GetString(originalstring);
printf("Please enter the pattern:\n");
GetString(patternstring);
printf("Please enter the replacement:\n");
GetString(replacement);
StringReplace(originalstring, patternstring, replacement);
printf("The Resultant string is %s\n", originalstring);
}
void StringReplace(char *original, char *pattern, char *replacement){
for(int i = 0; *(original + i) != '\0'; i++){
if(*(pattern) == *(original + i)){
for(int x = 0; *(pattern + x) == *(original + i + x); x++){
if(x == 1){
*(original + i + (x - 1)) = *(replacement + (x - 1));
*(original + i + x) = *(replacement + x);
}
if(x >= 2){
*(original + i + x) = *(replacement + x);
}
}
}
}
} // this is supposed to replace the pattern string with the replacement string if they have 2 or more similar characters in succession