I am making a code that needs a way to capitalize the first two letters of a given string. Example: if input string is aplle it should be outputted as APple.
Any sugguestions?
1 2 3 4 5 6 7 8 9
cin>>nme;
if(nme!="CN"||"Cn") //if string begins with CN or Cn
{
nme[0] = toupper(nme[0]); //capitalize first letter
}
else
{
//function to capitalize first two letters
}
its exactly what you think it would be..
if the string has 2 letters or more,
then nme[0] and nme[1], the first 2 letters, need uppercase.
you may want to check for empty strings for the first part too...
if(nme!="CN"||"Cn") //if string begins with CN or Cn
Each condition in an if statement must be independent, you need a condition in the part after the || as well.
But... your if statement doesn't make much sense in the first place.
Perhaps you want to use substring?
The correct syntax and logic would be:
// Example program
#include <iostream>
#include <string>
bool StartsWith(const std::string& str, const std::string substr)
{
if (str.length() < substr.length())
returnfalse;
return str.substr(0, substr.length()) == substr;
}
int main()
{
std::string name = "CNabbl";
if (StartsWith(name, "CN") || StartsWith(name, "Cn"))
{
std::cout << "Starts with CN\n";
}
else
{
std::cout << "Doesn't start with CN\n";
}
}
Of course, the above code doesn't actually answer your question of capitalizing the first two letters of the string. You're doing the wrong check. Like jonnin said, if the string has 1 letter, just capitalize the 1st letter, and if the string has more than 1 letter, capitalize the first two letters. Simple.
Also... just a note on variable naming: what is the point of removing the 'a' in "name"? It adds no value to the code, and just makes it harder to read. It's okay to have vowels in variable names :)
Each condition in an if statement must be independent, you need a condition in the part after the || as well.
Thanks i forgot that.
what is the point of removing the 'a' in "name"? It adds no value to the code, and just makes it harder to read. It's okay to have vowels in variable names
its supposed to be non-metal, i'm making a program for chemistry.
I'll check tomorrow when i have time for other possible answers, thanks.