四、String类的转换功能

来源:互联网 发布:php curl 获取图片 编辑:程序博客网 时间:2024/06/05 15:59
/* * String的转换功能: * byte[] getBytes():把字符串转换为字节数组。 * char[] toCharArray():把字符串转换为字符数组。 * static String valueOf(char[] chs):把字符数组转成字符串。 * static String valueOf(int i):把int类型的数据转成字符串。 * 注意:String类的valueOf方法可以把任意类型的数据转成字符串。 * String toLowerCase():把字符串转成小写。 * String toUpperCase():把字符串转成大写。 * String concat(String str):把字符串拼接。 */public class StringDemo {public static void main(String[] args) {// 定义一个字符串对象String s = "JavaSE";// byte[] getBytes():把字符串转换为字节数组。byte[] bys = s.getBytes();for (int x = 0; x < bys.length; x++) {System.out.println(bys[x]);}System.out.println("----------------");// char[] toCharArray():把字符串转换为字符数组。char[] chs = s.toCharArray();for (int x = 0; x < chs.length; x++) {System.out.println(chs[x]);}System.out.println("----------------");// static String valueOf(char[] chs):把字符数组转成字符串。String ss = String.valueOf(chs);System.out.println(ss);System.out.println("----------------");// static String valueOf(int i):把int类型的数据转成字符串。int i = 100;String sss = String.valueOf(i);System.out.println(sss);System.out.println("----------------");// String toLowerCase():把字符串转成小写。System.out.println("toLowerCase:" + s.toLowerCase());System.out.println("s:" + s);// System.out.println("----------------");// String toUpperCase():把字符串转成大写。System.out.println("toUpperCase:" + s.toUpperCase());System.out.println("----------------");// String concat(String str):把字符串拼接。String s1 = "hello";String s2 = "world";String s3 = s1 + s2;String s4 = s1.concat(s2);System.out.println("s3:"+s3);System.out.println("s4:"+s4);}}

/* * 需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符) * 举例: * helloWORLD * 结果: * Helloworld *  * 分析: * A:先获取第一个字符 * B:获取除了第一个字符以外的字符 * C:把A转成大写 * D:把B转成小写 * E:C拼接D */public class StringTest {public static void main(String[] args) {// 定义一个字符串String s = "helloWORLD";// 先获取第一个字符String s1 = s.substring(0, 1);// 获取除了第一个字符以外的字符String s2 = s.substring(1);// 把A转成大写String s3 = s1.toUpperCase();// 把B转成小写String s4 = s2.toLowerCase();// C拼接DString s5 = s3.concat(s4);System.out.println(s5);// 优化后的代码// 链式编程String result = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());System.out.println(result);}}

0 0
原创粉丝点击