如何将字符串转换为大写的c ++

时间:2015-03-31 16:45:39

标签: c++

我不允许使用toupper()

这些是我的函数,一个函数必须通过引用传递字符串。

void Uppercase(string x)
{
int y = 0;
while (y < x.length)
{
    x[y] = x[y] - 32;
    y++;
}
}

void uppercase(string &x)
{
int y = 0;
while (y < x.length)
{
    x[y] = x[y] - 32;
    y++;
}

我至少有正确的想法吗?

我在构建它时遇到此错误....

错误5错误C2446:'&lt;' :没有转换'unsigned int(__thiscall std :: basic_string,std :: allocator&gt; :: *)(void)throw()const'到'int'c:\ users \ edwingomez \ documents \ visual studio 2013 \ projects \ homework \ homework \ homework6.cpp 18 1作业

5 个答案:

答案 0 :(得分:3)

由于使用toupper的限制让我感到愚蠢和适得其反,我可能会以这样一种方式回应这种任务,这种方式遵循禁止的信件,同时撇开其显而易见的意图,像这样:

#include <locale>
#include <iostream>

struct make_upper : private std::ctype < char > {
    void operator()(std::string &s){
        do_toupper(&s[0], &s[0]+s.size());
    }
};

int main() { 
    std::string input = "this is some input.";
    make_upper()(input);
    std::cout << input;
}

这当然会产生预期的结果:

THIS IS SOME INPUT.

与我在此处发布的其他答案不同,这仍然具有使用toupper的所有常规优势,例如在使用EBCDIC而非ASCII编码的计算机上工作。

与此同时,我想我应该承认(例如)当我五年级的时候,我曾被告知要做类似的事情,写下“我不会在课堂上讲话”#39 ;,50次。&#34;所以我把一篇含有一句话的论文翻了过来,#34;我不会在课堂上讲50次。&#34; Mary Ellen姐妹(是的,天主教学校)并不是特别高兴。

答案 1 :(得分:1)

使用std::transformlambda expression功能是一种方法:

std::string s = "all uppercase";
std::transform(std::begin(s), std::end(s), std::begin(s),
    [](const char& ch)
    { return (ch >= 'a' && ch <= 'z' ? ch - 32 : ch) });
std::cout << s << '\n';

应输出

ALL UPPERCASE

如果系统使用ASCII字符集(或ch - 32表达式会产生意外结果)。

答案 2 :(得分:0)

这是对的。但是你应该注意在输入上添加检查。您可以检查字符是否是小写字母。

if (x[y] <= 'z') && (x[y] >= 'a')
    x[y] = x[y] - 32;

为了便于阅读,您应该将32替换为'a' - 'A'

另外,你的第一个功能什么也没做。它会创建字符串的副本。是否需要采取相应措施。然后丢弃它,因为你没有返回它,函数结束。

答案 3 :(得分:0)

示例代码:

  • 正确检查范围。
  • 使用C ++ 11版本(使用range-for-loop)。

注意:生产版本应该使用toupper。但OP明确指出无法使用。

代码:

#include <iostream>

const char upper_difference = 32;

void uppercaseCpp11(std::string& str) {
    for (auto& c : str) {
        if (c >= 'a' && c <= 'z')
            c -= upper_difference;
    }
}

std::string UppercaseCpp11(std::string str) {
    uppercaseCpp11(str);
    return str;
}

void uppercase(std::string& x) {
    for (unsigned int i = 0; i < x.size(); ++i) {
        if (x[i] >= 'a' && x[i] <= 'z')
            x[i] -= upper_difference;
    }
}

std::string Uppercase(std::string x) {
    uppercase(x);
    return x;
}

int main() {
    std::cout << Uppercase("stRing") << std::endl;
    std::string s1("StrinG");
    uppercase(s1);
    std::cout << s1 << std::endl;

    std::cout << UppercaseCpp11("stRing") << std::endl;
    std::string s2("StrinG");
    uppercaseCpp11(s2);
    std::cout << s2 << std::endl;

    return 0;
}

答案 4 :(得分:0)

    string x = "Hello World";
    char test[255];
    memset(test, 0, sizeof(test));
    memcpy(test, x.c_str(), x.capacity());
    for (int i = 0; i < x.capacity(); i++)
    {
        if (test[i] > 96 && test[i] < 123)
            test[i] = test[i] - 32;
    }

    x.assign(test);
相关问题