문제

Hey I tried to make a look up table to switch chars to upper case:

struct X {
    static const char lut[256];
};

int main(int argc, char** argv) {
    for(int i = 0; i < 256; i++) {
        char c = (char)i;
        if (c <= 'z' && c > 'Z') {
            X::lut[i]= (c-32);  
        }
        X::lut[i]=c;
    }
    return 0;
}

I know that this is the wrong way:( Can someone show me to do this correct?

도움이 되었습니까?

해결책

You may use the following (in C++11):

#include <array>
#include <cctype>

std::array<char, 256> to_upper_array()
{
    std::array<char, 256> res;

    for (int i = 0; i != 256; ++i) {
        res[i] = char(std::toupper(i));
    }
    return res;
}

struct X {
    static const std::array<char, 256> lut;
};

const std::array<char, 256> X::lut = to_upper_array();

다른 팁

While you have the question tagged as C++, the code seems to be more in line with C. If you are using C++, the comment to use std::toupper by Jarod42 is a great suggestion.

If you are trying to do it as C, then I believe your if statement is not correct. Consider the case of where c is just one greater than 'Z', which would be the '[' character. In that case you are subtracting 32 which is not probably what you would like to do. I would change the if to do just the range of lower characters.

In addition, even if your if is run, the next statement following the if block will set the character back to c, so you need to add an else statement and block, or do the assignment before you do the comparison to change to the look-up table.

Your condition looks a bit weird - there are several other characters between 'Z' and 'a' - and you're overwriting the table entry immediately when the condition is true. You're going to need an else to handle the characters that shouldn't be translated.

    if ('a' <= c && c <= 'z') {
        X::lut[i] = c - 32;  
    } 
    else { 
        X::lut[i] = c;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top