Java开发笔记(三十六)字符串的常用方法

不管是给字符串赋值,还是对字符串格式化,都属于往字符串填充内容,一旦内容填充完毕,则需开展进一步的处理。譬如一段Word文本,常见的加工操作就有查找、替换、追加、截取等等,按照字符串的处理结果异同,可将这些操作方法归为三大类,分别说明如下。

一、判断字符串是否具备某种特征

该类方法主要用来判断字符串是否满足某种条件,返回true代表条件满足,返回false代表条件不满足。判断方法的调用代码示例如下:

String hello = "Hello World. ";
// isEmpty方法判断该字符串是否为空串
boolean isEmpty = hello.isEmpty();
System.out.println("isEmpty = "+isEmpty);
// equals方法判断该字符串是否与目标串相等
boolean equals = hello.equals("你好");
System.out.println("equals = "+equals);
// startsWith方法判断该字符串是否以目标串开头
boolean startsWith = hello.startsWith("Hello");
System.out.println("startsWith = "+startsWith);
// endsWith方法判断该字符串是否以目标串结尾
boolean endsWith = hello.endsWith("World");
System.out.println("endsWith = "+endsWith);
// contains方法判断该字符串是否包含了目标串
boolean contains = hello.contains("or");
System.out.println("contains = "+contains);

运行以上的判断方法代码,得到以下的日志信息:

isEmpty = false
equals = false
startsWith = true
endsWith = false
contains = true

二、在字符串内部进行条件定位

该类方法与字符串的长度有关,要么返回指定位置的字符,要么返回目标串的所在位置。定位方法的调用代码如下所示:

String hello = "Hello World. ";
// length方法返回该字符串的长度
int length = hello.length();
System.out.println("length = "+length);
// charAt方法返回该字符串在指定位置的字符
char first = hello.charAt(0);
System.out.println("first = "+first);
// indexOf方法返回目标串在该字符串中第一次找到的位置
int index = hello.indexOf("l");
System.out.println("index = "+index);
// lastIndexOf方法返回目标串在该字符串中最后一次找到的位置
int lastIndex = hello.lastIndexOf("l");
System.out.println("lastIndex = "+lastIndex);

运行以上的定位方法代码,得到以下的日志信息:

length = 13
first = H
index = 2
lastIndex = 9

三、根据某种规则修改字符串的内容

该类方法可对字符串进行局部或者全部的修改,并返回修改之后的新字符串。内容变更方法的调用代码举例如下:

String hello = "Hello World. ";
// toLowerCase方法返回转换为小写字母的字符串
String lowerCase = hello.toLowerCase();
System.out.println("lowerCase = "+lowerCase);
// toUpperCase方法返回转换为大写字母的字符串
String upperCase = hello.toUpperCase();
System.out.println("upperCase = "+upperCase);
// trim方法返回去掉首尾空格后的字符串
String trim = hello.trim();
System.out.println("trim = "+trim);
// concat方法返回在末尾添加了目标串之后的字符串
String concat = hello.concat("Fine, thank you.");
System.out.println("concat = "+concat);
// substring方法返回从指定位置开始截取的子串。只有一个输入参数的substring,从指定位置一直截取到源串的末尾
String subToEnd = hello.substring(6);
System.out.println("subToEnd = "+subToEnd);
// 有两个输入参数的substring方法,返回从开始位置到结束位置中间截取的子串
String subToCustom = hello.substring(6, 9);
System.out.println("subToCustom = "+subToCustom);
// replace方法返回目标串替换后的字符串
String replace = hello.replace("l", "L");
System.out.println("replace = "+replace);

运行以上的内容变更方法代码,得到以下的日志信息:

lowerCase = hello world. 
upperCase = HELLO WORLD. 
trim = Hello World.
concat = Hello World. Fine, thank you.
subToEnd = World. 
subToCustom = Wor
replace = HeLLo WorLd. 

更多Java技术文章参见《Java开发笔记(序)章节目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值