java中的String类的详细用法

详细用法件代码:

public class StringDemo {

public static void main(String args[]){
String a = "Wellcome to our school!!"; //通过定义字符串常量实例化一个字符串对象
String b = new String(); //构造方法一,定义一个空的字符串序列
String c = new String("    HeLlo Java   "); //构造方法二,利用已经存在的String常量作为参数新建String对象
char d[] = {'w','e','a','r','e','t','h','e','s','a','m','e'};
String f = new String(d); //构造方法三,通过字符数组的内容初始化建立String对象
String  h = new String(d,2,3);//构造方法四,从指定的位置开始,将此处开始的n个字符作为初始化的内容,建立String对象
System.out.println("(1)"+h);
System.out.println("(2)"+"the length of a is "+a.length()); //public int length(),计算字符串的长度
System.out.println("(3)"+c+"->"+c.toLowerCase());//public String toLowercase(),将字符串中的所有大写字母转化为小写字母
System.out.println("(4)"+c+"->"+c.toUpperCase());//public String toUppercase(),将字符串中的所有小写字母转化为大写字母
System.out.println("(5)"+c.trim());//public String trim(),去掉前导空格与末尾的空格
System.out.println("(6)"+a.substring(11));//public String substring(int beginIndex),返回当前字符串beginIndex到结束的子串
System.out.println("(7)"+a.substring(11,14));//public String substring(int beginIndex, int endIndex),返回当前字符串从beginIndex到endIndex的字符串
System.out.println("(8)"+b.replace(' ','a'));//public String replace(int oldChar,int newChar),将当前字符串中出现的所有的oldChar的字符用newChar替代
System.out.println("(9)"+f.charAt(2)); //public String charAt(int Index),返回1~length-1中指定位置的字符
char[] dst = new char[45];
f.getChars(2,4,dst,0); //public void getChars(int srtBegin, in srtEnd, char dst[], int dstBegin),
System.out.println("(10)"+dst[0]);
String s1 = "HELLO WORLDS";
String s2 = "hello worlds";
String s3 = "hello";
System.out.println("(11)"+s1.equalsIgnoreCase(s2));//public boolean equalIgnoreCase(String another),忽略字母的大小写,比较两个字符串是否相等,若相等则返回true,否则返回false
System.out.println("(12)"+s1.compareTo(s3));//public int compareTo(String anotherString),比较两个字符串的大小返回一个大于,小于或者等于0的数
System.out.println(a.toCharArray()); //public char[] toCharArray(),将一个字符串转化为一个字符数组
System.out.println("(14)"+a.getBytes()); //public byte[] getByte(),将当前字符串转化成一个字节数组
System.out.println("(15)"+a.startsWith("well"));//public boolean startsWith(String prefix),判断当前字符串是不是以prefix开头
System.out.println("(16)"+a.endsWith("school!!"));//public boolean endsWith(String prefix),判断当前 字符串是不是以prefix结尾
System.out.println("(17)"+a.indexOf('l'));//public int indexOf(char ch),返回ch字符在字符串中第一次出现的位置,否则返回-1
System.out.println("(18)"+a.lastIndexOf('l'));//public int lastIndexOf(char ch),返回当前字符串最后出现指定ch字符的位置
}
}

 

运行结果:

(1)are
(2)the length of a is 24
(3)    HeLlo Java   ->    hello java   
(4)    HeLlo Java   ->    HELLO JAVA   
(5)HeLlo Java
(6) our school!!
(7) ou
(8)
(9)a
(10)a
(11)true
(12)-32
Wellcome to our school!!
(14)[B@773de2bd
(15)false
(16)true
(17)2
(18)21

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值