较低的字符串字符,并在转换后的大写字母前添加_

时间:2014-02-02 15:23:37

标签: c++ algorithm tolower

我还有一个问题,我想在每个大写字母前添加一个_,它将被转换为小写字母,加上第一个字母不能是资本!!我无法弄清楚如何做到......:{例如:

输入: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");
}

编辑&gt;

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;
}
                      }

1 个答案:

答案 0 :(得分: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;
}