简体   繁体   中英

printing first letter of C++ string arrays

Hey Guys I 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

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.

for( auto s : arr )
{
   char x = s.front();
   if( x =='R' ||  x== 'r' )
   {
       std::cout << s << '\n';
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM