String 常用方法

切换大小写

System.out.println("WIN64".toLowerCase(Locale.forLanguageTag("tr-TR")));    // wın64   土耳其语
System.out.println("linux64".toUpperCase(Locale.forLanguageTag("tr-TR")));  // LİNUX64 土耳其语
System.out.println("WIN64".toLowerCase(Locale.ROOT));                       // win64   不对应任何语言,采用通用的格式
System.out.println("linux64".toUpperCase(Locale.ROOT));                     // LINUX64 不对应任何语言,采用通用的格式

获取字符

char c = "abc".charAt(0);            // c
char[] chars = "abc".toCharArray();  // abc

截取

String str = "abcdefg";
System.out.println(str.substring(0)); // abcdefg
System.out.println(str.substring(2)); // cdefg
System.out.println(str.substring(6)); // g
System.out.println(str.substring(7)); // 空 下标没有7但是不报错
System.out.println(str.substring(8)); // java.lang.StringIndexOutOfBoundsException: String index out of range: -1
System.out.println(str.substring(-1)); // java.lang.StringIndexOutOfBoundsException: String index out of range: -1

String str = "abcdefg";
System.out.println(str.substring(0, 1));             // a
System.out.println(str.substring(0, 0));             // 空
System.out.println(str.substring(0, str.length()));  // abcdefg
System.out.println(str.substring(0, str.length() + 1)); // java.lang.StringIndexOutOfBoundsException: String index out of range: 8
System.out.println(str.substring(-1, str.length()));    // java.lang.StringIndexOutOfBoundsException: String index out of range: -1

分割

String[] split(String regex, int limit)
# 其中regex为分割正则表达式,limit为分割次数限制;

# limit=1时:表示把字符串分割成1份
String[] strLst = "1,2,3,4".split(",", 1);  // [1,2,3,4]

# limit=2时:表示把字符串分割成2份
String[] strLst = "1,2,3,4".split(",", 2);  // [1, 2,3,4]

# limit=4时:表示把字符串分割成4份
# limit=5时:表示把字符串分割成4份、但是最多只能分4分、会自动分4分
String[] strLst = "1,2,3,4".split(",", 4);  // [1, 2, 3, 4]

# limit=0时:字符串被尽可能多的分割,但是尾部的空字符串会被抛弃
String[] strLst = "1,2,3,4,".split(",", 0);  // [1, 2, 3, 4]

# limit < 0时:字符串被尽可能多的分割,而且尾部的空字符串不会被抛弃
String[] strLst = "1,2,3,4,".split(",", -1);  // [1, 2, 3, 4, ]
String[] split(String regex)
# 对于没有 limit 参数的 split函数,等价于 limt = 0 的情况,尾部的空字符串被舍弃掉

其他

contains(CharSequence s)
length()
replace()
format()

参考

String最常用方法
java split(String regex, int limit) 和 split(String regex)的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值