- import java.util.Scanner;
- import javax.swing.text.ChangedCharSetException;
- /**
- * 从键盘接收一个字符串,对字符串中的字母进行大小写互转(大写字母转成小写,小写字母转成大写)。
- */
- public class Test7{
- public static void main(String[] args)
- {
- System.out.println("请输入一串字母:");
- Scanner sc = new Scanner(System.in);
- String inputStr = sc.nextLine();
- String outputStr = convert(inputStr);
- System.out.println(inputStr+"\n大小写转换后:\n"+outputStr);
- }
- public static String convert(String sourceStr){
- char[] targetStr = new char[sourceStr.length()];
- for(int i=0;i<sourceStr.length();i++){
- int ascii = (int)sourceStr.charAt(i);//得到字母对应的ascii码
- if(ascii>=97){//小写
- targetStr[i] = (char)(ascii-32);
- }else if(ascii>=65){//大写
- targetStr[i] = (char)(ascii+32);
- }
- }
- return String.valueOf(targetStr);
- }
- }
复制代码
|
|