您的位置:首页 > 其它

学习总结-String类常用API

2014-02-11 21:28 381 查看
创建字符串对象

String students = "小明"; //寻找已建字面量

String students1 = new String("小明"); //另辟空间,创建新的字面量

System.out.println(students.equals(students1)); //输出为false

获取字符串的长度

String he = "hello,my name is dahai!";

System.out.println(he.length()); //输出结果为23 ,包含在字符串内的标点和空格也计算在内

连接字符串

格式1:string1.concat(string2); //返回一个新的字符串,新字符串为string1后面添加上string2

String string1 = "hello";

String string2 = ",my name is dahai!";

System.out.println(string1.concat(string2));

格式2:System.out.println("hello".concat(",my name is dahai!")); //可以直接通过字符串字面量调用concat()方法

格式3:System.out.println("hello"+",my name"+" is dahai!"); //当+用在字符串中间时,意思是将多个字符串合并在一起生成一个新的字符串

以上输出结果皆为hello,my name is dahai!

字符数组与字符串之间的相互转化

字符数组转化为字符串:

char[] loveArray = {'I','l','o','v','e','y','o','u'};

String loveArray1 = new String(loveArray);

System.out.println(loveArray1); //输出结果为Iloveyou

字符串转化为字符数组:

String loveArray = "Iloveyou";

char[] loveArray1 = loveArray.toCharArray(); //字符数组为{'I','l','o','v','e','y','o','u'};空格也算一个字符

操纵一个字符串中的字符

通过索引获得一个字符或字符串:

String abc = "abcdefghigklmn";

char a = abc.atChar(6); //字符串中第7个字符 输出为g

String b = abc.substring(7,13); //字符串中第8到第13字符但不包括第13个 输出为higkl

String c = abc.substring(9); //字符串中第8个字符到最后的字符 输出为higklmn

操纵字符串的其他方法

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: