2017-02-10 9 views
1

私は、このようなCの文字配列の途中に複数の文字を挿入するにはどうすればよいですか?

char line[50] = "this is a string"; 

と、余分なスペースを毎回追加

line[counter] == ' '; 

としてchar配列をループは、このようにすべてのスペースを持つ文字列が得られことができますどのように把握しようとこだわっています2倍の長さです。

+2

最も簡単な方法は、別の配列を作成してそこに結果を書き込むことです。 –

+1

スペースを挿入し、そのスペースの後のすべての文字を各ループステップで明示的にシフトする必要があります。もちろん、一時コピーを使用することもできます。 – Shiping

+0

デバッグヘルプ(「なぜこのコードは動作しませんか?)」には、目的の動作、特定の問題またはエラー、および質問自体に再現するのに必要な最短コードが含まれている必要があります。明確な問題文がない質問は、他の読者にとって有用ではありません。参照:最小、完全、および検証可能な例を作成する方法。 – Olaf

答えて

1

最初に空白文字の数を数え、その文字列を逆方向にコピーする必要があります。

#include <stdio.h> 

int main(void) 
{ 
    char s[50] = "this is a string"; 

    puts(s); 

    size_t n = 0; 
    char *p = s; 

    do 
    { 
     if (*p == ' ') ++n; 
    } while (*p++); 

    if (n != 0) 
    { 
     char *q = p + n; 

     while (p != s) 
     { 
      if (*--p == ' ') *--q = ' '; 
      *--q = *p; 
     } 
    } 

    puts(s); 

    return 0; 
} 

ためのプログラム出力は

this is a string 
this is a string 

、より効率的なアプローチである。ここで、以下の

#include <stdio.h> 

int main(void) 
{ 
    char s[50] = "this is a string"; 

    puts(s); 

    size_t n = 0; 
    char *p = s; 

    do 
    { 
     if (*p == ' ') ++n; 
    } while (*p++); 

    for (char *q = p + n; q != p;) 
    { 
     if (*--p == ' ') *--q = ' '; 
     *--q = *p; 
    } 

    puts(s); 

    return 0; 
} 
0

は、別の文字列を用いた溶液である:

#include <stdio.h> 

int main(void) { 
    char line[50] = "this is a string"; 
    char newline[100]; //the new string, i chose [100], because there might be a string of 50 spaces 
    char *pline = line; 
    char *pnewline = newline; 
    while (*pline != NULL) { //goes through every element of the string 
    *pnewline = *pline; //copies the string 
    if (*pline == ' ') { 
     *(++pnewline) = ' '; //adds a space 
    } 
    pline++; 
    pnewline++; 
    } 
    printf("%s", line); 
    printf("%s", newline); 
    return 0; 
} 

メモリを使い切ることができない場合は、このすべてを動的メモリ割り当てとfree()「一時的な」文字列で行うことができます。あなたは配列を使っていたので、私は今それをしなかった。

関連する問題