字符串的常见用法

来源:互联网 发布:梅西 c罗 知乎 编辑:程序博客网 时间:2024/05/16 17:44
//把一个字符串变为一个字符数组class Haha{public static void main(String args[]){String name =  "Hello";char c[] = name.toCharArray();for(int i = 0; i < c.length;i++){System.out.println(c[i]);}}}


(2)把字符数组变为字符串

//把一个字符串变为一个字符数组class Haha{public static void main(String args[]){char c[] = {'h','e','l','l','o'};String name = new String(c);String name_1 = new String(c,0,3);//0代表从角标为0开始,显示角标为0,1,2的3个字符System.out.println("显示全部的字符:"+name);System.out.println("显示从0开始的3个字符:"+name_1);}}


(3)从字符串取出指定位置的字符

class Haha{public static void main(String args[]){String name = "hello";System.out.println("取出角标为2的字符:"+name.charAt(2));}}


(4)字符串与byte数组的转换

class Haha{public static void main(String args[]){String name = "hello";byte b[] = name.getBytes();//将字符串变为byte数组System.out.println(new String(b));//将字符串数组变为String类型System.out.println(new String(b,0,3));//将角标为0开始的3个字符串变为String类型}}

(5)计算字符串的长度
//在这里,很多人会把计算字符串的长度与计算数组长度的方法混淆//计算数组的长度是:数组.length//计算字符串的长度是:字符串.length()class Haha{public static void main(String args[]){String name = "hello";System.out.println(name+"的长度是:"+name.length());}}

(6)查找字符串是否存在指定内容
//indexOf返回的是一个int类型的数据,表示它在哪个位置//若没有查找到,则返回-1class Haha{public static void main(String args[]){String name = "hellohello";System.out.println(name.indexOf("o",0));//从角标为0开始查找,但只会查找第一个o,后面的o不会查找System.out.println(name.indexOf("o",5));//只有过了第一个o,才会查找下一个oSystem.out.println(name.indexOf("a"));//没有查找到,返回-1}}

(7)字符串去掉空格
//trim()只能去掉字符串左右的空格,并不能去掉字符串内的空格class Haha{public static void main(String args[]){String name = "           h  e  l  l  o  h  e  l  l  o       ";System.out.println("去掉左右空格之后的字符串:"+name.trim());//输出的是h  e  l  l  o  h  e  l  l  o}}

(8)字符截取
//trim()只能去掉字符串左右的空格,并不能去掉字符串内的空格class Haha{public static void main(String args[]){String name = " hello";System.out.println("从角标为2的字符开始截取"+name.substring(2));//输出:elloSystem.out.println("截取从角标0到第5个字符前(不包括第5个,即o)的字符:"+name.substring(0,5));//输出:hell}}

(9)分割字符串
class Haha{public static void main(String args[]){String name = " h e l l o ";String s[] = name.split("e");for(int i = 0; i < s.length;i++){System.out.println(s[i]);}}}//输出:h //      e l l o

(10)大小写转换
class Haha{public static void main(String args[]){String name = "hello";String name_1 = "HELLO";System.out.println("将\"hello\"转换为大写"+name.toUpperCase());System.out.println("将\"HELLO\"转换为小写"+name_1.toLowerCase());}}

(11)是否以指定的字符串开头或者结尾
//判断是否以指定字符串结尾或者开头,返回的是true或者falseclass Haha{public static void main(String args[]){String name = "hello";System.out.println("判断\"hello\"是否以he开头:"+name.startsWith("he"));System.out.println("判断\"hello\"是否以he结尾:"+name.endsWith("he"));}}

(12)不区分大小写的比较,equals是区分大小写的
class Haha{public static void main(String args[]){String name = "hello";String name_1 = "HELLO";System.out.println(name+"与"+name_1+"的比较结果:"+name.equalsIgnoreCase(name_1));}}//输出结果:true




0 0