如何在特殊字符(如Å)上使用tolower或toupper?

huangapple go评论66阅读模式
英文:

How to use tolower or toupper with a special character such as Å

问题

在使用C语言编程时,我遇到了关于tolower和toupper函数的问题。
我想要打印一个大写字母 'Å',然后使用tolower函数打印一个小写字母 'å'。

首先,我声明一个变量 int x,并给它赋值为 143(因为在ASCII中,'Å' 对应该整数)。然后,我使用 printf("%c", x) 打印出 x,我将得到一个 'Å'。我还想要打印一个 'å'(小写的 'Å'),为此我使用了 tolower 函数。然而,我并没有得到 'å',而是得到了两个 'Å',我不明白为什么会这样。如果有人能够解释给我,我将不胜感激。另外,我是编程新手,因此可能不时使用不正确的术语,但希望你能理解!

以下是我的代码:

#include <stdio.h>
#include <ctype.h>

int main(void){

int x = 143;

printf("大写是 %c\n", x);
printf("小写是 %c\n", tolower(x));

return 0;
}

输出:

大写是 Å
小写是 Å

我也尝试过以下代码,但输出结果相同:

#include <stdio.h>
#include <ctype.h>

int main(void){

int x = 143;
int y;

y = tolower(x);

printf("大写是 %c\n", x);
printf("小写是 %c\n", y);

return 0;
}
英文:

While programming in C, I encountered a problem regarding the tolower and toupper functions.
I want to print an upper case 'Å', and then using the tolower function to print a lower case 'Å' ('å').

First, I declare a variable int x, and give it a value of 143 (because in the ASCII, Å is given that integer). When I then print out x using printf("%c", x) I will get an 'Å'. I also want to print an 'å' (a lower case Å), and to do so, I used the tolower function. However, I do not get an 'å', I only get 2 Å's and I do not understand why. If someone could explain it to me I will be grateful. Also, I am new to programming. Thus I might not use the correct terms at all times, but hopefully you will understand!

Here is my code:

#include &lt;stdio.h&gt;
#include &lt;ctype.h&gt;

int main(void){

int x = 143;

printf(&quot;Upper case is %c\n&quot;, x);
printf(&quot;Lower case is %c\n&quot;, tolower(x));

return 0;
}

Output:

Upper case is Å
Lower case is Å

I also tried this, but the output was the same:

#include &lt;stdio.h&gt;
#include &lt;ctype.h&gt;

int main(void){

int x = 143;
int y;

y = tolower(x);

printf(&quot;Upper case is %c\n&quot;, x);
printf(&quot;Lower case is %c\n&quot;, y);

return 0;
}

答案1

得分: 2

请看:tolower

返回值

ch的小写版本,如果在当前C语言环境中没有列出小写版本,则返回未修改的ch。

由于你得到了未修改的值,这意味着在当前C语言环境中找不到小写版本。

为了解决这个问题,一个解决方案可能是通过setlocale设置适当的C语言环境。

此外,我建议阅读以下两篇文章,因为值143不是ASCII而是扩展ASCII(并且以便更好地理解setlocale的用途):

英文:

Have a look at: tolower
> Return value
>
> Lowercase version of ch or unmodified ch if no lowercase version is listed in the current C locale.

Since you get the unmodified value, that means no lowercase version was found.

To fix the problem, a solution might be to set the appropriate C locale (via setlocale).

Furthermore, i would suggest to read the following two articles, since the value 143 is not ASCII but Extended ASCII (and to get a better understanding what setlocale is good for):

huangapple
  • 本文由 发表于 2023年1月9日 06:03:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定