2016-01-20 100 views
-8

如標題所示,我想使用C-樣式而不是使用庫string來插入字符在char array之後,並且請避免使用緩衝區函數,只有基本的:)。在字符數組中的特定位置插入一個字符

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,和insertingChar = '*';

結果應該是:「我wa * nt a * pples」。

+0

使用'std :: string'使您的生活更輕鬆。 –

+0

在您的示例中,只有1個'a's'受到影響,是否是由設計決定的? –

+0

nope我有一個問題,當發佈這個,是一個*之後的第一個'a' – JohnnyOnPc

回答

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; 
    } 
} 
+0

@SergeyA,沒有更多:) – milevyo

+0

假設,當然,有原始緩衝區中的所有添加字符的空間。或者*「使用std :: string讓你的生活更輕鬆。」* –

相關問題