关于字符串
题目是这样:
给定一个字符串“张三,男,50;李四,男,37;王丫,女,21”
要求打印出如下结果
姓名 性别 年龄
张三 男 50
李四 男 37
王丫 女 21
我写的程序如下
String s = "张三,男,50;李四,男,37;王丫,女,21 ";
String[] str = s.split( "; ");
StringBuffer s1 = new StringBuffer(str[0]);
s1.replace(2, 3, " ");
s1.replace(4, 5, " ");
StringBuffer s2 = new StringBuffer(str[1]);
s2.replace(2, 3, " ");
s2.replace(4, 5, " ");
StringBuffer s3 = new StringBuffer(str[2]);
s3.replace(2, 3, " ");
s3.replace(4, 5, " ");
System.out.println( "姓名 " + " " + "性别 " + " " + "年龄 ");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
虽然结果一样,但是我觉得我理解题目的意思可能错误了,它不应该是单单的一个打印问题吧
大家都是什么意见呢?
------解决方案--------------------或者如果你用jdk1.5以上的版本,想格式输出的话也可以这样写:
public class Test
{
public static void main(String[] args)
{
String s= "张三,男,50;李四,男,37;王丫,女,21 ";
System.out.format( "%1$10s%2$10s%3$10s ", "姓名 ", "性别 ", "年龄 ");
System.out.println();
String[] persons=s.split( "; ");
for (int i=0;i <persons.length; i++ )
{
String[] detail=persons[i].split( ", ");
System.out.format( "%1$10s%2$10s%3$10s ",detail[0],detail[1],detail[2]);
System.out.println();
}
}
}