c - 更改C中字符的大小写
问题描述
#include <stdio.h>
#include <string.h>
char changeincase(int, int, int);
int main() {
int size, index1, index2;
char string[1000], newstring[1000];
printf("enter the size of the string :");
scanf("%d", &size);
printf("Enter the string : ");
scanf("%s", string);
printf("Enter the first index :");
scanf("%d", &index1);
printf("Enter the second index :");
scanf("%d", &index2);
newstring[5] = changeincase(index1, index2 ,size);
printf("%s", newstring);
}
char changeincase(i, j, n) {
char str[1000];
if (str[i] >= 65 && str[i] <= 90) {
str[i] = str[i] + 32;
}
if (str[j] >= 65 && str[j] <= 90) {
str[j] = str[j] + 32;
}
}
上面的代码应该在指定索引处转换字符串的大小写,但它不起作用。每次我运行代码时,它都会生成一些随机字符。请帮帮我。
解决方案
You could invert case for a single character with a following function:
#include <ctype.h>
int invert_case(int c) {
if (islower(c)) return toupper(c);
else if (isupper(c)) return tolower(c);
else return c;
}
This code avoids using magic constants.
Another issue is updating a local variable str
. The changes are invisible outside the function. Just make str
an argument:
void changeincase(char* str, int i, int j) {
// char str[1000];
...
}
推荐阅读
- c - 以下实用程序的宏与函数的用法
- c - 编写一个程序来检查一个数字是否是阿姆斯壮和神奇的,或者两者都不是使用函数
- swift - 使用 DisclosureGroup 时的 SwiftUI List 与 ForEach
- android - 在通过 Android WebRTC 流式传输视频时拍摄高分辨率(本地)照片?
- ruby - 如何检查 nil 并比较 != nil on Hashes?
- javascript - Next.js 得到混淆的 API 响应
- r - 自动扩展网页的折叠部分以在 R 中进行网页抓取
- php - 运行 composer install 时内存不足
- java - 将十进制int转换为二进制
- python - 如何在matplotlib中修改数字堆叠在一起的x轴