String类的进一步学习二

本文通过一个具体的Java字符串操作实例,详细解析了`replaceFirst`和`substring`方法的使用细节及常见误区,帮助读者理解如何正确地进行字符串替换与截取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在对一个字符串进行操作的时候比较悲剧,基础不牢固,捣鼓了半天。

public class StringTest { public static void main(String[] args) { String path="/mnt/sdcard/gao.txt"; path.replaceFirst("/mnt", ""); System.out.println(path); String pathSub="/mnt/sdcard/gao.txt"; pathSub.substring(3, pathSub.length()); System.out.println(pathSub); } }

期望了结果是:

/sdcard/gao.txt /sdcard/gao.txt

但是实际的结果却是:

/mnt/sdcard/gao.txt /mnt/sdcard/gao.txt

看一下API的解释:

String java.lang.String.replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern.compile(regex).matcher(str).replaceFirst(repl)

Parameters:

regex the regular expression to which this string is to be matched

replacement

Returns:

The resulting String

这下该明白了是返回的那个值才是想要的结

修改后:

String pathSub="/mnt/sdcard/gao.txt"; pathSub=pathSub.substring(3, pathSub.length()); System.out.println(pathSub);

满以为这下返回的结果该是:/sdcard/gao.txt,可是返回的结果却是:t/sdcard/gao.txt

再看一下API的解释:

String java.lang.String.substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Examples:

"hamburger".substring(4, 8) returns "urge"

"smiles".substring(1, 5) returns "mile"

Parameters:

beginIndex the beginning index, inclusive.

endIndex the ending index, exclusive.

Returns:

the specified substring.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值