c++ 中的大写到小写
我正在尝试将字符串从小写转换为大写,在 C++ 上则相反。所有这一切都没有使用库,而是使用 ascii 代码。 我的问题是我不知道如何获取字符的ascii代码,更改它,然后再次将其转换为字符。我只知道如何通过打印来完成它,但我需要在内存上进行这种转换。 我该怎么做?
这是我尝试过的:
char* invertirCase(char* str){
int len = strlen(str);
int i;
int valor;
for (i = 0; i <= len; i++) {
valor = (int)str[i];
if (valor >= 65 && valor <= 90) {
valor = valor + 32;
str[i] = (char)valor;
}
else if (valor >= 97 && valor <= 122) {
valor = valor - 32;
str[i] = (char)valor;
}
}
return str;
}
I'm trying to transform a string of characters from lower to upper case and the other way round on c++. All this without using libraries, and using ascii code instead.
My problem is I don't know how to get the ascii code of a character, change it, and then transform it to character again. I only know how to do it by printing it, but I need to do this transformation on the memory.
How can I do this?
This is what I've tried:
char* invertirCase(char* str){
int len = strlen(str);
int i;
int valor;
for (i = 0; i <= len; i++) {
valor = (int)str[i];
if (valor >= 65 && valor <= 90) {
valor = valor + 32;
str[i] = (char)valor;
}
else if (valor >= 97 && valor <= 122) {
valor = valor - 32;
str[i] = (char)valor;
}
}
return str;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在程序中使用强制转换运算符是多余的。
另外,如果要编写,for 循环中的条件
通常看起来会更正确
,因为
str[len]
会生成您所在字符串的终止零字符'\0'
无论如何都不会改变。使用
65
这样的幻数并不是一个好主意。在不使用标准函数的情况下,可以按以下方式定义函数
Using the cast operator in your program is redundent.
Also the condition in the for loop
will look more correctly in general if to write
because
str[len]
yields the terminating zero character'\0'
of the string that you are not going to change in any case.And it is a bad idea to use magic numbers like
65
.Without using standard functions the function can be defined the following way