简体   繁体   English

C ++ toUpper Implementation

[英]C++ toUpper Implementation

I made an implementation of toUpper(). 我做了一个toUpper()的实现。 It doesn't work 100%. 它不起作用100%。

Code : 代码:

char* toUpper(char* string)
{
    char* sv = string;
    while(*sv++ != '\0')
    {
        if( int(*sv) >= 97 || int(*sv) <= 122)  //Only if it's a lower letter
            *sv = char( *sv - 32);
    }
    return string;
}

I know that the lower letters have the numbers from 97 to 122 (in ASCII) and the upper letters have the numbers from 65 to 90. There are exactly 32 numbers between the lower to the upper letter. 我知道低位字母的数字从97到122(ASCII格式),高位字母的数字从65到90.低位到高位字母之间正好有32个数字。 So I just subtracted 32 from the lower character. 所以我只是从较低的字符减去32。

Code where I call this function : 我调用此函数的代码:

char h[] = "Whats up?";
cout << toUpper(h) << endl;

I expected the program to output "WHATS UP?" 我希望程序输出“WHATS UP?” but instead I got "WHATS" . 但相反,我得到了“什么” What did I do wrong? 我做错了什么?

if( int(*sv) >= 97 || int(*sv) <= 122)

should be 应该

if( int(*sv) >= 97 && int(*sv) <= 122)

or, preferably 或者,最好是

if( *sv >= 'a' && *sv <= 'z')
    *sv = *sv - ('a' - 'A');

You also need to move the point at which you increment sv . 您还需要移动增加sv的点。 The current code skips checking the first character in string 当前代码跳过检查string的第一个字符

while(*sv != '\0')
{
    if( *sv >= 'a' && *sv <= 'z')
        *sv = *sv - ('a' - 'A');
    sv++;
}

Lastly, I'm sure you're aware of it but just in case... if this isn't a homework assignment or other learning exercise, the standard C toupper function will do exactly the same job for you 最后,我确定你已经意识到这一点,但以防万一...如果这不是作业或其他学习练习,标准C toupper功能将为你做同样的工作

*sv = (char)toupper(*sv);

Having ++ in the while makes you miss important cases. 拥有++,让你错过重要的案例。 The int() things are unnecessary noise. int()的东西是不必要的噪音。 You need && in the check condition. 在检查条件下你需要&&。 The action can be written with -=. 可以使用 - =写入操作。

Here's a rewrite that uses a for loop and fixes your conditional as well as off-by-one increment: 这是一个重写,使用for循环并修复您的条件和逐个增量:

char* toUpper(char* string)
{
    for(char* p=string; *p != '\0'; p++)
    {
        if(*p >= 'a' && *p <= 'z')  //Only if it's a lower letter
          *p -= 32;
    }
    return string;
}

re: "I expected the program to output "WHATS UP?" but instead I got "WHATS". What did I do wrong?" re:“我希望程序输出”WHATS UP?“但是我得到了”WHATS“。我做错了什么?” You didn't supply the code that is defective. 您没有提供有缺陷的代码。 If I had to guess, in main you are calling argv[1], But I am only guessing as your main is not included. 如果我不得不猜测,主要是你在调用argv [1],但我只猜测你的主要内容不包括在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM