首页 > 解决方案 > 更改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;
    }
}

上面的代码应该在指定索引处转换字符串的大小写,但它不起作用。每次我运行代码时,它都会生成一些随机字符。请帮帮我。

标签: c

解决方案


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];
...
}

推荐阅读