中断For循环C ++

时间:2018-03-22 18:27:30

标签: c++ loops for-loop break

我有这段代码

#include <iostream>
#include <string> 

using namespace std;

int main() {
    string text, findstring, replacestring;
    int i = -1;
    cout << "Text eingeben: ";
    getline( cin, text ); 
    cout << "findstring: ";
    cin >> findstring; 
    cout << "replacestring: "; 
    cin >> replacestring;
    if( text.find( findstring, 0 ) == -1 ) {
        cout << "Fehler: findString ist nicht vorhanden" << endl;
        return 1;
    }
    cout << endl;
    for (i; i>text.length();++i) {
        i =    text.find( findstring, i+1 );

            cout << "String " << findstring << " gefunden an Pos: " << i << endl;
            text.replace( i, findstring.length(), replacestring );

    }
    cout << "Ergebnis: " << text << endl;
    cout << text.length();
    return 0;
}

在另一个字符串中搜索字符串并返回其位置并将其替换为另一个字符串。现在我的问题是,当目标字符串在原始字符串中被多次包含时,为什么这不起作用?我尝试使用do ... while循环,它工作得很好。我想知道如何用for循环来做到这一点。

1 个答案:

答案 0 :(得分:0)

这有点棘手。将itext.length()进行比较会导致错误。 i是值为-1的int,而text.length()unsigned type,因此-1 is always > text.length()。这就是为什么您的for loop只运行一次(当i仍为-1时)。

这是一种可能的修复方法(在我的机器上运行良好):

#include <iostream> 
#include <string>

using namespace std;

int main() {
    string text, findstring, replacestring;
    int i = -1;

    cout << "Text eingeben: ";
    getline(cin, text);
    cout << "findstring: ";
    cin >> findstring;
    cout << "replacestring: ";
    cin >> replacestring;

    if( text.find( findstring, 0 ) == -1 ) {
        cout << "Fehler: findString ist nicht vorhanden" << endl;
        return 1;
    }

    cout << endl;

    do {
        i = text.find(findstring, i + 1);
        if (i == -1) {
            cout << "No more result found" << endl;
            break;
        } else {
            cout << "String " << findstring << " gefunden an Pos: " << i << endl;
            text.replace(i, findstring.length(), replacestring);
        }

    } while (true);
    cout << "Ergebnis: " << text << endl;
    cout << text.length() << endl;
    return 0;
}