C++ 每个单词的首字母必须大写

Posted

技术标签:

【中文标题】C++ 每个单词的首字母必须大写【英文标题】:C++ First letter of every word must be uppercased 【发布时间】:2021-12-04 17:49:06 【问题描述】:

我是一名学生,刚接触编程

我正在尝试将每个单词的第一个字母大写,其余的小写。

当前的输出是即使我输入了 2 个或更多单词,也只打印了第一个单词。

#include <iostream>
#include <cstring>

using namespace std;

int main()

    int i;
    char str[100];
    char rev;
    int len = 0;

    cout << "Enter a string: ";
    cin >> str;
    
    len = strlen(str);
    
    for (i = 0; i < len; i++)
    
        if (i == 0)
        
            str[i] = toupper(str[i]);
        
        else
        
            str[i] = tolower(str[i]);
        
        cout << str[i];
    

【问题讨论】:

提示,读完后尝试打印 str 并验证你读过的内容。 您的问题可能与:***.com/questions/5838711/stdcin-input-with-spaces 这并没有解决问题,但int len = 0; ... len = strlen(str); 应该是int len = strlen(str);。用无意义的值初始化对象并立即覆盖该值是没有意义的。只需将其初始化为您需要的值即可。 【参考方案1】:

请注意,您的代码仍然有更多的“c”风味,而不是“c++”风味。 仍然可以使用管理您自己的数组的大小和使用索引, 但最好留给标准库的类。因此,如果您想要一个字符串,请使用 std::string 而不是 char str[100];另请注意,字符串有一个长度方法,不需要将字符串转换为字符数组。 看看这个例子:

#include <string>
#include <set>
#include <iostream>

// do not teach yourself to type : using namespace std.
// just type std:: in front of every std type
// it will avoid problems in bigger projects later

// for anything you do make a function with a readable name.
// pass by value so we get a copy of the string to work on.
std::string capitalize(std::string string)

    // create a static set of unique characters that will
    // be used to recognize where new words begin.
    // I added a few, maybe more are needed. 
    static std::set<char> delimiters ' ', ',', '.', '\n' ;

    // first character of a sentence should always be uppercase
    bool make_next_char_uppercase = true;

    // loop over all the characters in the input string.
    // this is called a range based for loop and is 
    // an improvement over the indexed for loop
    // used since "C", this style of loop can't go outside
    // the bounds of the array.
    // use a reference so we can modify the characters in place
    for (char& c : string)
    
        if (make_next_char_uppercase) c = toupper(c);
        
        // the next line of code is C++20 syntax.
        // but it means that if you encounter a word delimiter
        // then the next character read must be changed to uppercase.
        make_next_char_uppercase = delimiters.contains(c);

        // for earlier versions of C++ use
        //make_next_char_uppercase = (std::find(delimiters.begin(), delimiters.end(), c) != delimiters.end());
    

    return string;


int main()

    auto output = capitalize("the quick brown fox jumps over the lazy dog!\nalso text after a newline and a,should be uppercase!");
    std::cout << output;

【讨论】:

【参考方案2】:
#include <iostream>
#include <cstring>
using namespace std;
int main()

int i;
char str[100];
char rev;
int len = 0;

cout << "Enter a string: ";
cin.getline(str, 100);

len = strlen(str);

for (i = 0; i < len; i++)

    if (i == 0)
    
        str[i] = toupper(str[i]);
    
    if (str[i] == ' ')
    
        str[i + 1] = toupper(str[i + 1]);
    
    cout << str[i];


【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。【参考方案3】:

std::cin 看到空格时停止阅读。如果您想读到换行符,请使用getline()。此外,与在 C++ 中一样,使用 std::string 而不是 C 样式的字符串。而且你不应该使用using namespace std;,因为它被认为是不好的做法,如here所示。

我的“推荐”代码:

#include <iostream>
#include <string>
#include <cctype>
int main()

    std::string str;
    char rev;

    std::cout << "Enter a string: ";
    getline(std::cin, str);

    int len str.size();

    for (int i = 0; i < len; i++)
    
        if (i == 0)
        
            str[i] = toupper(str[i]);
        
        if (str[i] == ' ')
        
            str[i + 1] = toupper(str[i + 1]);
        
        std::cout << str[i];
    

【讨论】:

【参考方案4】:

正如其他人所指出的,一旦std::cin 遇到空格,它将停止读取。

下面的代码仍然一次读取 1 个单词。我喜欢它本质上是如何为您进行字符串拆分,而无需您付出太多努力。

然后我使用iterator's 来遍历std::string 中的字符。

需要skip 函数来删除stream 中的任何空格,以便我可以检查换行符(\n)。如果检测到换行符,则break 退出循环。

static std::istream& skip( std::istream& stream ) 

    static const std::set<char> needles ' ', '\t', '\r', '\v' ;
    while ( needles.find( static_cast<char>( stream.peek( ) ) ) != needles.end( ) ) 
    
        stream.ignore( );
    
    return stream;


int main( ) 

    const auto to_upper [ ]( auto begin, auto end )  
        std::transform( begin, end, begin, [ ]( unsigned char c )  
            return std::toupper( c );
         );
     ;

    const auto to_lower [ ]( auto begin, auto end )  
        std::transform( begin, end, begin, [ ]( unsigned char c )  
            return std::tolower( c );
         );
     ;

    std::cout << "Enter a strings\n";

    for( std::string input ; std::cin >> input; ) 
    
        to_upper( input.begin( ), input.begin( ) + 1 );
        to_lower( input.begin( ) + 1, input.end( ) );
    
        std::cout << input << ' ';
        if ( std::cin >> skip && std::cin.peek( ) == '\n' ) 
        
            std::cout << '\n';
            break;
        
    

【讨论】:

以上是关于C++ 每个单词的首字母必须大写的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Perl 中将字符串中每个单词的首字母大写?

将数据框列中每个单词的首字母大写

将一句英文中每个单词的首字母大写,其余字母小写。

使用流畅的语法将每个单词的首字母大写?

如何使用 JavaScript 将字符串中每个单词的首字母大写?

使用 Vim 将所选内容中每个单词的首字母大写