Convert first letter in string to uppercase

后端 未结 5 1015
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 23:27

I have a string: \"apple\". How can I convert only the first character to uppercase and get a new string in the form of \"Apple\"?

I can al

相关标签:
5条回答
  • 2020-12-02 23:56
    #include <iostream>
    using namespace std;
    
    void capitalize (string &s)
    {
        bool cap = true;
    
        for(unsigned int i = 0; i <= s.length(); i++)
        {
            if (isalpha(s[i]) && cap == true)
            {
                s[i] = toupper(s[i]);
                cap = false;
            }
            else if (isspace(s[i]))
            {  
                cap = true;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 00:00

    Like what Carneigie said,

    string str = "something";
    str[0] = toupper(str[0]);
    

    but also remember to:

    #include <string>
    #include <cctype>
    

    all the way up

    0 讨论(0)
  • 2020-12-03 00:02

    (Only works with 'ASCII' characters.)

    std::wstring s = L"apple";
    
    if(islower(s.at(0) <= 'z' ? s.at(0) : 'A'))
        s[0] += 'A' - 'a';
    

    Or if you are feeling fancy and feel like torturing any future readers of your code:

    std::wstringstream wss;
    wss << std::uppercase   << s[0]
        << std::nouppercase << s.substr(1);
    wss >> s;
    
    0 讨论(0)
  • 2020-12-03 00:11

    I cannot use str[0] because, I can have string which has multibyte characters

    I don't know of any CRT implementation that supports non-ASCII character classification and conversion. If you want to support Unicode then everything is much more complicated since "converting the first character to uppercase" may be meaningless in other languages. You have to use a Unicode library written by experts for this.

    To illustrate how complicated it is, consider the following case in English. Converting the three code-point sequence 'file' (with f-i ligature) shall break the first codepoint into two separate letters resulting in 'File'. Please note that the standard C/C++ interfaces for doing case classification and conversion don't take such cases into account, so it's even impossible to implement them to support Unicode correctly.

    0 讨论(0)
  • 2020-12-03 00:15
    string str = "something";
    str[0] = toupper(str[0]);
    

    That's all you need to do. It also works for C strings.

    0 讨论(0)
提交回复
热议问题