0

我还有一个问题,我想在每个大写字母前加一个_,它会被转换为小写,而且第一个字母不能是大写!我不知道该怎么做... :{ 示例:

输入:loLollL,输出:lo_loll_l,我也希望它倒退:输入:lo_loll_l 输出:loLollL

代码在这里:

#include <iostream>
#include <algorithm>

using namespace std;

int main ()
{
    const int max = 100;
    string slovo;
    int pocet_r;

    cout << "Zadaj pocet uloh:" << endl;
    cin >> pocet_r;

    if(pocet_r >= 1 && pocet_r <=100)
 {

     // funkcia na zabezpecenie minimalneho poctu chars
          for (int i = 0; i <pocet_r; i++)
     {
           cout << "Uloha " << i+1 << ":" << endl; 

                cin >> slovo;

                if(slovo.size() > max)
                {
                 cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
                }
                 while( slovo.size() > max) 
                 {
                  cin >> slovo;
                 }      

                 for (int i=0; i <= slovo.size(); i++)
                 {
                   int s = slovo[i];
                   while (s > 'A' && s <= 'Z')
                   {
                      if(s<='Z' && s>='A'){
                      return s-('Z'-'_z');
                      }else{

                      cout <<  "chyba";

                      }
                   } 


                }


           cout << slovo[i] << endl;   

     }   

 }else{
     cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}

编辑>

for (int i=0; i <= slovo.size(); i++)
            {
                while (slovo[i] >= 'A' && slovo[i] <= 'Z')
                {
                      string s = transform(slovo[i]);

    cout << s << endl;

    s = untransform(s);

    cout << s << endl;
}
                      }
4

1 回答 1

0

这应该有效:

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

using namespace std;

string
transform(const string& s)
{
    const size_t n = s.size();
    string t;

    for (size_t i = 0; i < n; ++i)
    {
        const char c = s[i];

        if (isupper(c))
        {
            t.push_back('_');
        }

        t.push_back(tolower(c));
    }

    return t;
}

string
untransform(const string& s)
{
    string t;

    const size_t n = s.size();
    size_t i = 0;

    while (i < n)
    {
        char c = s[i++];

        if (c != '_')
        {
            t.push_back(c);
            continue;
        }

        c = s[i++];

        t.push_back(toupper(c));
    }

    return t;
}

int
main()
{
    string s = transform("loLollL");

    cout << s << endl;

    s = untransform(s);

    cout << s << endl;
}
于 2014-02-02T15:39:13.770 回答