5. 区分字符串大小写

题目

把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。

解题之法

#include <iostream>
#include <string.h>
using namespace std;
int main(){
    string s;
    while(cin >> s){
        if(s.length() >= 1 && s.length() <= 1000){
            for(int i = 0; i < s.length(); i++)
                if(s[i] >= 'a' && s[i] <= 'z')
                    cout << s[i];
            for(int i = 0; i < s.length(); i++)
                if(s[i] <= 'Z' && s[i] >= 'A')
                    cout << s[i];
            cout << endl;//
        }
    }
    return 0;
}

分析

上述解法是取巧,只为输出字符串,如果要想交换大小写位置,给出下面这种解法:

#include<iostream>
#include<string>
using namespace std;
 
bool isCap(char c)
{
    if (c >= 'A' && c <= 'Z')
        return true;
    else
        return false;
}
  
void mSwap(char &a, char &b)
{
    if (a != b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}
  
int main()
{
    string s;
    while (cin >> s)
    {
        int len = s.size();
        int end = len;
        for (int i = 0; i<end; ++i)
        {
            if (isCap(s[i]))
            {
                int j = i;
                for (; j<len- 1; ++j)
                    mSwap(s[j], s[j + 1]);
                --end;
                --i;
            }
        }
        cout << s <<endl;
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容