- /*
- 编写程序,从键盘接收一个字符串,对字符串中的字母进行大小写互转(大写字母转成小写,小写字母转成大写)。
- */
- package com.itheima;
- import java.util.Scanner;//导入Scanner类
- public class Test06
- {
- public static void main(String[] args)
- {
- System.out.print("请从键盘上输入一段字符串:");
- Scanner sc=new Scanner(System.in);//建立Scanner类对象,键盘输入语句
- String s=sc.next();//将输入字符串赋值到String类型的s变量中
- StringTool.stringSwap(s);
- }
- }
- class StringTool//将字符串转换封装为一个类
- {
- //建立小写字母表
- private static char[]ch1={'a','b','c','d','e','f','g',
- 'h','i','j','k','l','m','n',
- 'o','p','q','r','s','t','u',
- 'v','w','x','y','z'};
- //建立大写字母表
- private static char[]ch2={'A','B','C','D','E','F','G',
- 'H','I','J','K','L','M','N',
- 'O','P','Q','R','S','T','U',
- 'V','W','X','Y','Z'};
- //封装字符串大小写转化功能函数
- public static void stringSwap(String s)
- {
- char[]ch3=s.toCharArray();//将字符串转化为字符数组
- char[]ch4=new char[ch3.length];
- for(int x=0;x<ch3.length;x++)//通过for循环和if语句判断字符数组的元素是否能在字母表中找到,并进行转换
- {
- if(ch3[x]==lookFor(ch1,ch3[x]))
- ch4[x]=(char)((int)ch3[x]-32);
- if(ch3[x]==lookFor(ch2,ch3[x]))
- ch4[x]=(char)((int)ch3[x]+32);
- if(ch3[x]!=lookFor(ch1,ch3[x])&&ch3[x]!=lookFor(ch2,ch3[x]))
- ch4[x]=ch3[x];
- }
- System.out.println(new String(ch4,0,ch4.length));//通过String的构造函数将字符数组转化为字符串
- }
- //封装功能函数:寻找字符串中的字符在哪个表中
- private static char lookFor(char[]arr,char ch)
- {
- for(int x=0;x<arr.length;x++)
- if(ch==arr[x])
- return arr[x];
- return '0';
- }
- }
复制代码 |