【问题标题】:C++ How to capitalize first word of each sentence/line in a string?C ++如何将字符串中每个句子/行的第一个单词大写?
【发布时间】:2017-12-03 23:31:27
【问题描述】:

我现在正在掉头发。我有一个字符串,我操纵它在标点符号后开始一个新的行/句子,但我不明白如何将每个句子的第一个单词大写?除此之外,我无法跳出循环将点更改为点和换行。

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

【问题讨论】:

  • @Thesar 我的帖子对你有用吗?
  • 在我尝试@JakeFreeman 之前它已被删除。我现在就试试。
  • 还要确保在字符串之间放置\n 字符。
  • getline 属于哪个库?不能让它工作。错误:E0349 没有运算符“+”与这些操作数匹配 E0304 没有重载函数“getline”的实例与参数列表匹配 E0070 不允许不完整的类型(流)@JakeFreeman
  • 好的,让我知道@Thesar

标签: c++ string line capitalization


【解决方案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";
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2013-04-11
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多