Java-String类复习整理(String类常用方法)

//太久没用Java,对语法不熟悉了,大概整理复习下加深印象

tips:String类内部指向的串是常量,每次改变后会创建新的对象指向它,原来的可能被自动回收机制回收。

String经常改变尽量用StringBuilder那些...

直接写的字符串常量被当做String类的对象.

两个String对象内容相同指向的地址其实一样.

package test;
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s = new String("hello world");
		
		System.out.println(s.charAt(2));	//求指定下标对应字符
		
		System.out.println(s.substring(1));	//求从指定下标开始到结尾的子串
		
		System.out.println(s.substring(1,4));	//求指定下标之间的子串,区间左闭右开

		System.out.println(s.compareTo("hello worla"));	//字符串比较,返回二者字典序相减的值

		System.out.println(s.compareToIgnoreCase("Hello World"));	//字符串比较,忽略大小写

		System.out.println(s.equals("hello world"));	//比较字符串内容是否相同

		System.out.println(s.concat("123") + " 123");	//比较字符串连接效果和+号一样

		System.out.println(s.indexOf("worl"));	//查找子串或子字符第一次出现位置,没有出现返回-1

		System.out.println(s.toUpperCase());	//大小写转换

		System.out.println(s.replaceAll("h", "  "));	//字符串替换

		System.out.println(s.trim());	//去掉首尾空白符
		
		System.out.println(s.contains("hello"));	//是否包含字符串
		
		String[] t = s.split(" ");
		
		for (String string : t) {
			System.out.println(string);
		}

		System.out.println(String.valueOf(12.3));	//其它数据类型转换为string						
	}
}

输出结果:

l
ello world
ell
3
0
true
hello world123 123
6
HELLO WORLD
  ello world
hello world
true
hello
world
12.3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值