【问题标题】:upper to lower and vice-versa without loop in C++?从上到下,反之亦然,在 C++ 中没有循环?
【发布时间】:2016-09-30 19:13:47
【问题描述】:

输入:

abcdE

输出:

ABCDe

我正在为此代码寻找一种高效且代码更少的解决方案:

#include <iostream>   
#include <string>
using namespace std;

int main() {
    int len, ;
    string data;

    cin >> data;

    len = data.length();

    for (i = 0; i < len; i++)
        if (isupper(data[i]))
            data[i] = tolower(data[i]);
        else
            data[i] = toupper(data[i]);

    cout << data << endl;

    return 0;
}

【问题讨论】:

  • 是的,有:std::ctype::toupper(),您可以使用std::transform() 算法等来应用它。
  • 你也许可以用更少的行来写这个,但就效率而言,这是 O(N),因为你必须尽可能好地访问每个元素。

标签: c++ toggle toupper tolower


【解决方案1】:

我想你应该使用std::transform:

std::string str("abcdE");
std::transform(str.begin(), str.end(), str.begin(), [](char c) {
        return isupper(c) ? tolower(c) : toupper(c);
});

【讨论】:

  • 这实际上是一个循环,但更糟糕的是,它不是像优化 cpus 那样执行缓存的代码块,而是对每个字符执行匿名函数调用。这就像一个循环,但不是执行 X,而是在执行 X 的每次迭代中调用一个函数。它也失去了与旧 c++ 版本的兼容性。聪明的代价相当高昂。
【解决方案2】:

您还可以使用来自algorithm 库的std::for_each

#include <iostream>   
#include <string>
#include <algorithm>

int main() {
    std::string data = "AbcDEf";
    std::for_each(data.begin(), data.end(), [](char& x){std::islower(x) ? x = std::toupper(x) : x = std::tolower(x);});
    std::cout << data<< std::endl;
}

【讨论】:

  • 请不要对字符使用幻数。 C++ 的语法可以让你使用字符来代替。
  • @NathanOliver 我想这让你现在很开心。
  • 不,但我会删除反对票。 AFAIK 这仍然是一种破碎的方式。
  • 你为什么会有这种感觉?
  • 除了 ASCII 之外,还有其他字符集可以用于 C++,并且字母块不需要是连续的。只有数字块保证是连续的。
猜你喜欢
  • 2016-03-29
  • 2012-06-27
  • 2017-07-08
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
相关资源
最近更新 更多