使用指针算法将数组元素更改为用户输入

Changing elements of an array to user input with pointer arithmetic

我正在尝试向用户询问 3 个不同的字符串,如果第二个字符串是第一个字符串的一部分,它将用第三个字符串替换该部分。除此之外,我必须使用指针算法来索引任何 arrays/strings。例如:

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) != '[=14=]'; 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

您检查了一些条件。, 如果在原始字符串中找到模式字符串,则检查 size_of(s2) 和 size_of(s3)。如果 s3 >= s2 ,则只需从原始字符串中删除模式字符串并将其替换为 s3。否则,找到 s3 和 s2 之间的大小差异,然后仅从原始字符串中删除具有该大小差异的模式字符串。最后用 s3.Hope 替换该位置这可能有帮助:)