C-使用find()分解字符串
C - Breaking up a string using find()
我正在编写一个pig拉丁文转换器,它将字符串作为命令行参数,并将句子中的每个单词转换为pig拉丁文。我试图通过查找空格将字符串分解为单独的单词,但我用下面的代码得到的输出。。。老实说毫无意义。
它适用于第一个单词,但不会转换任何后续单词。所以"测试这个字符串"变成了"esttay this ay string 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'));
}
两个错误:
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
代码很混乱,因为您试图跳过已找到的单词,您试图从句子中删除已找到的词。做一个或另一个。
我可以建议您使用POSIX正则表达式库或PCRE吗?这将使单词的第一个和最后一个字母的交换变得简单。
通过交换第一个和最后一个集合组,可以替换诸如\b(\w+)(\w)\b之类的正则表达式