Convert first letter in string to uppercase

坚强是说给别人听的谎言 提交于 2019-11-27 20:34:59
string str = "something";
str[0] = toupper(str[0]);

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

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.

Like what Carneigie said,

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

but also remember to:

#include <string>
#include <cctype>

all the way up

(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;
Rye Bryant
#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;
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!