c++ - 提示用户为首字母缩略词程序输入字符串

标签 c++ string

程序会提示用户输入一个短语,然后根据这些单词创建一个首字母缩写词。与具有大写字母的传统首字母缩略词不同,字母的大小写保持不变。如果我要进入The Town Hall is old,我应该得到TTHio。我如何使用 isspace 来确保我的程序正常运行,因为如果多个空格彼此相邻,它不会组合字符?它也不能处理制表符。

#include "stdafx.h"
#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std; 
string create_acronym(string str); 
int main()
{
    cout << "This program tests the acronym function." << "\n"; 
    while (true)
    {
        cout << "\nPlease enter a string: "; 
        string str; 
        getline(cin, str); 
        if (str == "") 
        {
            break; 
        }
        cout << "\n\nThe acronym is \"" << create_acronym(str) << "\"" << "\n";
    } 
    return 0;
}
string create_acronym(string str) 
{
    string acronym = "";
    acronym = str.at(0); 
    for (int i = 0; i < str.length(); i++)
    {
        if (str.at(i) == ' ') 
        {
            acronym += str.at(i+1); 
        }
    }
    return acronym; 
}

最佳答案

请记住,您需要输出下一个非空格:

string create_acronym( const string & str ) 
{
    string acronym;
    bool use_next = true;        

    for ( char c : str )
    {
        bool space = isspace(c);
        if ( use_next && !space ) acronym += c;
        use_next = space;
    }
    return acronym; 
}

关于c++ - 提示用户为首字母缩略词程序输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32240254/

相关文章:

c# - 从 C++ 到 C# 的 3D vector 结构

c++ - openCV SurfFeatureDetector 是否在内部不必要地提取描述符?

Swift double 到字符串

C++ 模板类特化和结构

c++ - 如何保留 'first' 和 'second' 用 struct 替换 std::pair ?

Java - 交替替换逗号

python - 如何在 Pandas 重新采样中包含字符串

c - 读取字符串不起作用

c - 将大数字作为字符串进行操作

c++ - 在解决方案中用于项目时缺少 NuGet 包