Reputation: 5
Hey Guys I'm new to c++ and was wondering how I can print out the first letter of my array. Take a look below:
string arr[] = { "Ron", "Red", "Frun" };
for each (string var in arr)
{
if (var.front == "R")
{
cout << var << endl;
}
}
I would like to print out strings in the array that begin with the letter R like Red and Ron
Upvotes: 0
Views: 3290
Reputation: 5059
You can use indexing with brackets to pull out the character at any given index in a string. So, for your string var:
if (var[0] == 'R')
{
std::cout << var << std::endl;
}
Alternately, you could use the front() function, like so:
if (var.front() == 'R')
{
std::cout << var << std::endl;
}
Note that you're also making a mistake when you compare the first character to "R" - double quotations denote a string literal, not a char, and both indexing and front() return a char. Secondly, the code as you've written it, and I've modified it, only checks for capital R, so "red" or "ron" will not have any code executed on them.
Upvotes: 4
Reputation: 47824
for( auto s : arr )
{
char x = s.front();
if( x =='R' || x== 'r' )
{
std::cout << s << '\n';
}
}
Upvotes: 3