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

C++ How to capitalize first word of each sentence/line in a string?

本文关键字:句子 单词 第一个 字符串      更新时间:2023-10-16

我现在正在失去头发。我有一个字符串,我会在标点符号后操作以启动新的行/句子,但是我不明白如何将每个句子的第一个单词大写?除此之外,我无法离开循环将点更改为点和新线。

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";
}

一种非常简单的方法是:

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";
}

希望这会有所帮助。