题解 | #字符串变形#

字符串变形

https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e

#include <cctype>
#include<string>
// #include<stdio.h>
using namespace std;
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @param n int整型
     * @return string字符串
     */

    // 第一种方法
    string trans(string s, int n) {
        // write code here
        if (s.empty()) {
            return s;
        }

        string str_tmp;
        string str_return;
        char tmp;

        for (int i = 0; i <= s.size(); i++) 
        {

            if (s[i] != ' ' && s[i] != '\0') {

                tmp = s[i];
                if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
                    tmp = (s[i] >= 'a') ? s[i] - 32 : s[i] + 32;
                }
                str_tmp += tmp;

            }else{
                str_tmp.insert(0, " ");
                str_return.insert(0, str_tmp);
                str_tmp.clear();
            }
        }

        str_return.erase(0, 1);


        return str_return;
    }



    //第二种方法
    // string trans(string s, int n) {
    //     // 注意:参数 n 在当前代码中没有使用,如果不需要可以移除
    //     if (s.empty()) {
    //         return s;
    //     }

    //     string str_return;
    //     string str_tmp;
    //     char tmp;

    //     for(int i = 0; i <= s.size(); ++i) {
            
    //         tmp = s[i];

    //         if (tmp != ' ' && tmp != '\0') {
                
    //             if (islower(tmp)) {
    //                 toupper(tmp);
    //             }else{
    //                 tolower(tmp);
    //             }

    //             str_tmp += tmp;

    //         }else{
    //             str_tmp.insert(0, " ");
    //             str_return.insert(0, str_tmp);
    //             str_tmp.clear();
    //         }

    //     }


    //     return str_return;
    // }

};

全部评论

相关推荐

Rena1ssance_:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务