C ++如何大写字符串中每个句子/行的第一个单词?

时间:2017-12-03 23:31:28

标签: c++ string line capitalization

我现在正在失去我的头发。我有一个字符串,我操纵在标点后开始一个新的行/句子,但我不明白我怎么能把每个句子的第一个单词大写?除此之外,我无法摆脱循环将点更改为点和新行。

int main()
{
    string const txt1 = "Candy is good for your health.";
    string const text2 = "All kids should buy candy.";
    string const text3 = "Candy nowadays is a hit among kids.";
    string const text4 = "Every meal should include candy.";


    string text = text1 + text2 + text3 + text4;

    transform(text.begin(), text.end(), text.begin(), ::tolower);

    while (text.find("candy") != string::npos)
        text.replace(text.find("candy"), 3, "fruit");
    string_replace_all(text, ".", ".\n");

这是我到目前为止添加的内容:

string line, total = ""; istringstream stream(text);
while (getline(stream, line, '\n'))
{
    if (line.size() > 0)
        total += (char)toupper(line[0]) + line.substr(1) + "\n";
    else total += "\n";
}

1 个答案:

答案 0 :(得分:1)

一个非常简单的方法是:

string line, total = ""; istringstream stream(someString);
while(getline(stream, line, '\n')) 
{
    if(line.size() > 0) 
        total += (char)toupper(line[0]) + line.substr(1) + "\n";
    else total+= "\n";
}

希望这有帮助。