Java:不使用函数将大写转换为小写,反之亦然

时间:2017-02-12 06:47:37

标签: java string

所以,我们的老师在Java中给了我们一个具有以下条件的挑战:

  • 用户输入4个字符的字符串(字母,符号和数字,全部混合)
  • 如果字母为大写,则将其转换为小写,反之亦然。
  • 符号和数字保持不变。
  • 打印出结果。

但限制是你不能使用split()length()toUpperCase()这两个函数。

我的第一个想法是使用switch和每个字母的案例,但我想知道是否有更好的(阅读更短更智能)替代方案:

public class program {           
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        String text;

        System.out.println("Type in:");
        text = input.nextLine();

        switch(text){
            case "A":
                System.out.println("a");
                break;
            case "b":
                System.out.println("B");
                break;

        }
}

您怎么看?

2 个答案:

答案 0 :(得分:3)

是的,有更好的方法。首先,您需要检查它是否是大写或小写的字母:

char c;
if(c >= 'a' && c <= 'z') {   
    c = c - 32
} else if(c >= 'A' && c <= 'Z') {   
    c = c + 32
}

作为&#39; A&#39;的ASCII值是65岁,&#39; B&#39;是66等等,&#39; a&#39;的ASCII值是97等等。您需要更改每个字母的ASCII值。我希望这会有所帮助。

答案 1 :(得分:-1)

你可以循环String,然后检查这个条件:

// c => ith letter in String

if(c >='a' && c<='z') c = c-'a' + 'A';
else if(c>='A' && c<='Z') c = c-'A' + 'a';

// append c into new String
相关问题