Как я могу использовать функцию toupper или tolower в массиве строк - PullRequest
0 голосов
/ 19 января 2020

Мне было интересно, как использовать функцию toupper, чтобы пользователь мог вводить эти слова любым удобным для него способом.

    //fill in arrays
     word[0]  =  "VERY";
     word[1]  =  "MERRY";
     word[2]  =  "CHRISTMAS";
     word[3]  =  "EVERYONE";


    for (i= 0; i<4; i++)
    {
        word[i] = toupper(word[i]);
    }

    food[0]  =  "CANDY";
    food[1]  =  "CAKE";
    food[2]  =  "SOUP";
    food[3]  =  "COOKIE";


    for (j=0;j<4;j++)
      {
        food[j] = toupper(food[j]);
     } 


     cout<<"\n Pick a word it can either be VERY, MERRY, CHRISTMAS, EVERYONE (can be written in anyway)";
     cin>> word[i];


     cout<<"\n Pick a food, it can be CAKE,SOUP, CANDY, OR COOKIE, can be written anyway)";
     cin>> food[j];

И что означает эта ошибка

[Error] no matching function for call to 'toupper(std::string&)'

Ответы [ 3 ]

1 голос
/ 19 января 2020

Если у вас есть массив с типом элемента std::string, подобный этому

std::string word[] =  { "VERY", "MERRY", "CHRISTMAS", "EVERYONE" };

, то вы можете преобразовать все его элементы, например, в нижний регистр, следующим образом, используя диапазон на основе l oop

#include <string>
#include <cctype>

//…

for ( auto &s : word )
{
    for ( char &c : s ) c = tolower( ( unsigned char )c );
}

Вот демонстрационная программа.

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    std::string word[] =  { "VERY", "MERRY", "CHRISTMAS", "EVERYONE" };

    for ( const auto &s : word ) std::cout << s << ' ';
    std::cout << '\n';

    for ( auto &s : word )
    {
        for ( char &c : s ) c = std::tolower( ( unsigned char )c );
    }

    for ( const auto &s : word ) std::cout << s << ' ';
    std::cout << '\n';

    for ( auto &c : word[0] ) c = std::toupper( ( unsigned char )c );

    for ( const auto &s : word ) std::cout << s << ' ';
    std::cout << '\n';
}

Ее вывод

VERY MERRY CHRISTMAS EVERYONE 
very merry christmas everyone 
VERY merry christmas everyone 

Или вы можете использовать пользовательскую функцию, подобную этой.

#include <iostream>
#include <string>
#include <cctype>

std::string & change_string_case( std::string &s, bool upper_case = true )
{
    for ( auto &c : s ) c = upper_case ? std::toupper( static_cast<unsigned char>( c ) )
                                       : std::tolower( static_cast<unsigned char>( c ) );

    return s;
}

int main()
{
    std::string word[] =  { "VERY", "MERRY", "CHRISTMAS", "EVERYONE" };

    for ( auto &s : word ) std::cout << change_string_case( s, false ) << ' ';
    std::cout << '\n';
}

Вывод программы:

very merry christmas everyone 

Или вы можете написать две отдельные функции, например,

#include <iostream>
#include <string>
#include <cctype>

std::string & lowercase_string( std::string &s )
{
    for ( auto &c : s ) c = std::tolower( static_cast<unsigned char>( c ) );

    return s;
}

std::string & uppercase_string( std::string &s )
{
    for ( auto &c : s ) c = std::toupper( static_cast<unsigned char>( c ) );

    return s;
}

int main()
{
    std::string word[] =  { "VERY", "MERRY", "CHRISTMAS", "EVERYONE" };

    for ( auto &s : word ) std::cout << lowercase_string( s ) << ' ';
    std::cout << '\n';
    for ( auto &s : word ) std::cout << uppercase_string( s ) << ' ';
    std::cout << '\n';
}

Вывод программы:

very merry christmas everyone 
VERY MERRY CHRISTMAS EVERYONE 
1 голос
/ 19 января 2020

Есть несколько способов выполнить эту задачу. Вы можете сделать это с помощью transform из algorithm headerfile.

#include <algorithm>
void  toUpperCase(std::string& str)
{
     std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}

int main()
{
    std::string str = "hello";
    toUpperCase(&str);
    std::cout << str << std::endl;    // "HELLO WORLD"
}

Другим способом будет использование boost, предоставляемое boost/algorithm/string.hpp.

#include <boost/algorithm/string.hpp>
#include <string>

int main() {
    std::string str = "Hello World";

    boost::to_upper(str);   
    std::cout << str << std::endl;    // "HELLO WORLD"

    return 0;
}

. здесь .

1 голос
/ 19 января 2020

Я всегда заключаю их в удобные функции для моего собственного здравомыслия:

// uppercase a string
static inline string upper(string s) {
    std::transform(s.begin(), s.end(), s.begin(), [](int ch) { return std::toupper(ch); });
    return s;
}

Тогда вы можете просто применить их так, как хотели бы:

for (j=0; j < 4; j++) {
     food[j] = upper(food[j]);
}

Предполагая, что у вас есть массив строк.

...