在char数组中的特定位置插入一个字符

时间:2016-01-20 19:04:57

标签: c++ arrays character

正如标题所说,我想使用char array样式在C中插入另一个字符,而不是使用库string,请避免使用缓冲区函数好吧,只有基本的:)。

char sentence[100],*p = NULL;
cin.get(sentence,100);
char replaceChar; // after What character should we insert
cin>>replaceChar;
char insertingChar; // the character we are inserting after the replaceChar;
cin >> insertingChar ; 
p = strchr(sentence , replace);
while(p != NULL){
//and this is I could think of ...
}

所以我们说我们有这句话:"我想要苹果",replaceChar = a,insertChar =' *';

结果应该是:"我在* pples"

1 个答案:

答案 0 :(得分:2)

这会将字符向右移动,为插入留出空间。

void rshift( char *s ){
    int n = strlen( s);
    s[ n + 1] = 0;
    while( n ){
       s[ n ] = s[ n-1 ];
       n--;
    } 
}

int main(){

    char *p = strchr(sentence , replace);

    if( p ) {
         p++; // insert after 
         rshift( p );
         *p = insertingChar;
    }
}
相关问题