0

重複の可能性:
このコードを再帰的にしようとしていますが、何らかの理由で機能しません

RECURSIONを使用して複数のスペースを1つのスペースに変更するプログラムを作成しようとしていますが、誰か助けてもらえますか?例「a_______b」が「a_b」に変わるのは、私が長い間やろうとしているタスクです!誰か助けてもらえますか?

ここで私はこれを試しましたが、デザインは再帰に対して機能しないと思います

void text_r(char *str)
{
    char *dst = str;

            if(*str=='\0')return ;
            *dst++ = *str;
            if (isspace(*str)) {
                    do ++str; while (isspace(*str));
                    --str;
            }
          return text_r(str++);
} 

再帰せずにコードを記述しましたが、変換に問題があります

void compress_spaces(char * str){char * dst = str;

    for (; *str; ++str) {
            *dst++ = *str;
            if (isspace(*str)) {
                    do ++str; while (isspace(*str));
                    --str;
            }
    }
    *dst = 0;

}

4

3 に答える 3

0

最善の方法ではありませんが、これらの線に沿って何かを試してください

char* remove_space(char *str)
{
    char *dst = str;

    while(*str!=' ' ||*str !='\0')
        *dst++ = *str;
    if (isspace(*str)) {
            do ++str; while (isspace(*str));
            --str;
    }
  return strcat(dst,remove_space(str++));
}

文字を見つけて文字列に格納し、スペースに到達したら最初の文字を格納して残りを無視するというアイデアです。その後、新しい文字列を関数に再度送信できます。そして、新しい文字列と連結された結果を返します

PSおそらく上記のコードはコンパイルされませんが、これにアプローチする方法についての良いアイデアが得られるはずです。

少し詳しく説明します。

スペースまですべての文字を保存し、その後、連続するすべてのスペースを無視して、残りの文字列をクリーンな文字列を返す関数に送信する関数を作成します。次に、2つの文字列を結合して、より大きなクリーンな文字列を作成します。

于 2013-02-05T08:44:22.600 に答える
0

これが私の実装です。複数のスペースの各バンドを最後のスペース文字を保持することで置き換え、非スペース文字が見つかったときにそのバンドを削除します

void reduce(String s, int curIndex, int lastSpaceIndex)
    if (lastSpaceIndex != -1)
        if s[curIndex] is not a space
            then replace substring from s[lastSpaceIndex, curIndex-1] by a space
        else
            reduce(s, curIndex+1, lastSpaceIndex);
    else
        if s[curIndex] is not a space
            then reduce(s, curIndex+1, -1)
        else
            reduce(s, curIndex+1, curIndex)
于 2013-02-05T09:17:29.893 に答える
0

引数として2回指定された、同じポインターを使用する再帰バージョン( whileなどの反復部分を回避)

void recur(char *str, char *out) {
  if (*str!=' ' || str[1]!=' ') *out++ = *str;
  if (*str) recur(str+1, out);
}

パラメータが1つしかない再帰バージョン

void recur(char *str) {
  static char *out = NULL;
  if (out == NULL) out = str;
  if (*str!=' ' || str[1]!=' ') *out++ = *str;
  if (*str) recur(str+1);
}

反復バージョン

void iter(char *str) {
  char *out = str;
  do {
    if (*str!=' ' || str[1]!=' ') *out++ = *str;
  } while (*str++);
}

のように呼ばれる

  char str[] = "   abc  d e  f   ";
  // either recursive
  recur(str, str);
  // or iterative
  iter(str);
于 2013-02-05T09:54:32.123 に答える