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
#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;
}
}
}
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;
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.
string str = "something";
str[0] = toupper(str[0]);
That's all you need to do. It also works for C strings.