C - 使用find()分解字符串

时间:2013-11-20 10:50:11

标签: c++ string

我正在编写一个猪拉丁语转换器,它将一个字符串作为命令行参数,并将句子中的每个单词转换为pig latin。我试图通过查找空格将字符串分解为单个单词,但是我使用下面的代码输出...老实说没有意义。

它适用于第一个单词,但不会转换任何后续单词。因此,“测试这个字符串”变成“这是一个字符串ay。”

此时我们还没有涉及向量,因此解决方案必须相对简单。

有什么想法吗?

#include <iostream>
#include <string>

using namespace std;

void convertSentence(string sentence);
string pigLatinWord(string input);
bool isVowel(string input);

int main(int argc, char* argv[]) {

    if(argc != 2) {
        cout << "USAGE: " << argv[0] << " \"[sentence]\"" << endl;
    } else {
        string sentence(argv[1]);
        convertSentence(sentence);
    }

    return 0;
}

void convertSentence(string sentence) {
    string word = "", remainder = sentence, pigLatin = "";

    for(int i = sentence.find(" ",0); i != string::npos; i = sentence.find(" ",i)) {
        word = sentence.substr(0,i);
        pigLatin += pigLatinWord(word) + " ";
        sentence = sentence.erase(0,i);
        i++;
    }

    pigLatin += pigLatinWord(sentence);
    cout << pigLatin << endl;
}


string pigLatinWord(string input) {

    string word = "";

// If the first letter is a vowel, simply add "yay" to the end of it.
       if (isVowel(input)) {
            word = input + "yay";

//If the first letter is a consonant, add the first letter to the end,
//delete the first letter, then add "ay." - Credit to Tyler Sorrels
//CString/String solution post on Piazza. I had issues working with
//substrings, and this ended up being easier to read.
//But I did add a check for words that start with two consonants
//to cover all cases.
    } else {
        input += input.at(0);
        input = input.erase(0,1);
        word = input + "ay";
    }

    return word;
}

// Checks if the first letter of the word is a vowel.
// Returns true if yes, false if no.
bool isVowel(string input) {
     return ((input[0] == 'a') || (input[0] == 'e') || (input[0] == 'i') || (input[0]      == 'o') || (input[0] == 'a'));
}

3 个答案:

答案 0 :(得分:1)

两个错误:

for(int ...; ; i = sentence.find(" ",i)) { // next space find should start from 0.
        //..
        //..
        sentence = sentence.erase(0,i);// you should delete the current space found also.
        i++;
    }

将其更改为:

for(int ...; ; i = sentence.find(" ",0)) { 
        //..
        //..
        sentence = sentence.erase(0,i+1);
        i++;
    }

输出:

esttay histay tringsay

答案 1 :(得分:0)

代码很混乱,因为您试图跳过已经找到的单词,您试图删除已经从句子中找到的单词。做其中一个。

答案 2 :(得分:0)

我是否可以建议您使用POSIX正则表达式库或PCRE,这样可以简单地交换单词的第一个和最后一个字母。

\ b(\ w)(\ w +)(\ w)\ b等正则表达式可以通过交换第一个和最后一个集合组来替换