1

ワード プロセッサの前にタイピングを学んだ人は、文末のピリオドの後に 2 つのスペースを追加することがよくあります。文字列を受け取り、"." の後に 2 つのスペースがすべて出現する文字列を返す関数 singleSpaces を記述します。変更された単一のスペースに。)

これは私が持っているものです。私は何を間違っていますか?

#include <cmath>
#include <iostream>
using namespace std;



string forceSingleSpaces1 (string s) {
    string r = "";
    int i = 0;
    while (i < static_cast <int> (s.length()))  {
        if (s.at(i) != ' ')  {
            r = r + s.at(i);
            i++;
        } else  {
            r +=  ' ';
            while (i < static_cast <int> (s.length()) && s.at(i) == ' ')
                i++;
        }
    }
    return r;
}
4

3 に答える 3

2

ここで説明するように、文字列内の特定の文字列の出現を別の文字列に置き換える、より一般的な関数を(再)使用することができます。

#include <string>
#include <iostream>

void replace_all(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

int main() {
    std::string text = "I'm old.  And I use two spaces.  After periods.";
    std::string newstyle_text(text);
    replace_all(newstyle_text, ".  ", ". ");
    std::cout << newstyle_text << "\n";

    return 0;
}

アップデート

最先端を行くことを恐れていない場合は、TR1正規表現の使用を検討してください。このようなものが機能するはずです:

#include <string>
#include <regex>
#include <iostream>

int main() {
    std::string text = "I'm old.  And I use two spaces.  After periods.";
    std::regex regex = ".  ";
    std::string replacement = ". ";
    std::string newstyle_text = std::regex_replace(text, regex, repacement);

    std::cout << newstyle_text << "\n";

    return 0;
}
于 2012-04-23T00:43:40.737 に答える
2

あなたの課題では、テキスト内のすべてのダブルスペースではなく、ドットの後のダブルスペースについての話があります。したがって、コードを変更して、

  • ' ' ではなく '.' を待ちます。
  • いつ '。' 傍受されてから追加し、その後単一のスペースを追加します

このコードは、2 つのステート マシンと考えることができます。

状態 1 - '.' 以外でループしているときです。文字、この状態で、コードは見つかったすべての結果に追加します

状態 2 - '.' の場合 が見つかり、この状態で別のコードを使用し、「.」を追加します。結果に戻り、その正確に単一のスペースを取得します(見つかった場合)

このようにして、問題を2つのサブ問題に分割します

[編集] - ソースコードを変更のヒントに置き換えました

于 2012-04-22T23:30:42.930 に答える
0
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

//1. loop through the string looking for ".  "
//2. when ".  " is found, delete one of the spaces
//3. Repeat process until ".  " is not found.  

string forceSingleSpaces1 (string str) {
    size_t found(str.find(".  "));
    while (found !=string::npos){
        str.erase(found+1,1);
        found = str.find(".  ");
    }

    return str;
}

int main(){

    cout << forceSingleSpaces1("sentence1.  sentence2.  end.  ") << endl;

    return EXIT_SUCCESS;
}
于 2012-04-22T23:55:39.977 に答える