黑马程序员技术交流社区
标题:
字母进行大小写互转
[打印本页]
作者:
xiong910627
时间:
2014-9-3 21:10
标题:
字母进行大小写互转
本帖最后由 xiong910627 于 2014-9-5 12:24 编辑
编写程序,从键盘接收一个字符串,对字符串中的字母进行大小写互转(大写字母转成小写,小写字母转成大写)。
public class Test5 {
public static void main(String[] args) {
System.out.println("字母大小写互换,请输入后回车");
String arry;
String result="";
//获取键盘输入的字符串
Scanner sc = new Scanner(System.in);
arry=sc.nextLine();
//用正则表达式设定字符串范围
String regx1="[a-z]";
String regx2="[A-Z]";
System.out.println("转换如下");
for(int i=0;i<arry.length();i++)
{
String sub=arry.substring(i, i+1);
//判断是否是小写字母,是则转换为大写
if(sub.matches(regx1))
{
sub=sub.toUpperCase();
result+=sub;
}
//判断是否是小写字母,是则转换为小写
else if(sub.matches(regx2))
{
sub=sub.toLowerCase();
result+=sub;
}
//其他类型则直接输出
else
{
result+=sub;
}
}
System.out.println(result);
}
}
作者:
15579171087
时间:
2014-9-3 21:17
用了正则表达式,也可以直接用char值来改吧
作者:
xiong910627
时间:
2014-9-3 21:19
有代码吗?
作者:
iefegend
时间:
2014-9-3 22:01
看看。。
作者:
Sakuratossi
时间:
2014-9-3 22:23
根据上面的代码改了一小下:用字符数组改的
package lm.test;
import java.util.Scanner;
public class ExchangeULCaseLetter {
public static void main(String[] args) {
/* System.out.println("字母大小写互换,请输入后回车");
String arry;
String result="";
//获取键盘输入的字符串
Scanner sc = new Scanner(System.in);
arry=sc.nextLine();
//用正则表达式设定字符串范围
String regx1="[a-z]";
String regx2="[A-Z]";
System.out.println("转换如下");
for(int i=0;i<arry.length();i++)
{
String sub=arry.substring(i, i+1);
//判断是否是小写字母,是则转换为大写
if(sub.matches(regx1))
{
sub=sub.toUpperCase();
result+=sub;
}
//判断是否是小写字母,是则转换为小写
else if(sub.matches(regx2))
{
sub=sub.toLowerCase();
result+=sub;
}
//其他类型则直接输出
else
{
result+=sub;
}
}
System.out.println(result);
*/
System.out.println("字母大小写互换,请输入后回车");
Scanner scanner = new Scanner(System.in);
String src = scanner.nextLine();
// 把数据放到一个字符数组 2deHJkd
char[] chs = src.toCharArray();
//遍历数组,把字母大小写换掉
String result = "";
for(int i = 0; i < chs.length; i++)
{
//将字符转成字符串
String temp = Character.valueOf(chs[i]).toString();
if(temp.matches("[A-Z]")) //如果是大写,转成小写, 装入字符串
result += temp.toLowerCase();
if(temp.matches("[a-z]"))
result += temp.toUpperCase(); //如果是小写,转成大写, 装入字符串
else
result += temp; // 其他字符,原样装入字符串。
}
System.out.println(result);
}
}
复制代码
作者:
cs8630323
时间:
2014-9-4 15:42
不用这么复杂,字母大小写unicode相差32,把小写字母减32再转char就是大写
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2