java萌新的进化旅程08

String的十种常用类方法

这篇博客主要总结十种String的常用类方法,分别可以对String进行比较、分割、截取、替换、搜索等操作。

一、equals()方法

equals()方法的主要作用是判断两个字符串是否相等,返回值是boolean类型
源码如下:

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

语法如下:

str1.equals(String str2);

其中str1和str2是要比较的两个字符串对象

二、equalsIgnoreCase()方法

作用与equals()方法类似,但忽略了大小写的情况,比较判断两个字符串是否相等,返回值仍是boolean类型
源码如下:

public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}

语法如下:

str1.equalsIgnoreCase(String str2);

其中str1和str2是要比较的两个字符串对象

三、split()方法

使用split()方法可以使字符串按指定的分割符或字符串对内容进行分割,并将分割后的结果存放在字符串数组中。split()方法提供了两种字符串分割形式。
(1)split(String sign)
该方法可根据给定的分割符对字符串进行拆分。
源码如下:

public String[] split(String regex) {
return split(regex, 0);
}

语法如下:

str.split(String sign);

(2) split(String sign, int limit)
该方法可以根据给定的分割符对字符串进行拆分,并限定拆分次数。
源码如下:

public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx’s meta characters “.KaTeX parse error: Expected '}', got '&' at position 220: …ue.length == 1 &̲& …|()[{^?*+\”.indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == ‘\’ &&
(((ch = regex.charAt(1))-‘0’)|(‘9’-ch)) < 0 &&
((ch-‘a’)|(‘z’-ch)) < 0 &&
((ch-‘A’)|(‘Z’-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize–;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}

语法如下:

str.split(String sign,int limit)

sign:分割字符串的分割符,也可以使用正则表达式。
limit:限制的分割次数。

四、substring()方法

通过string类的substring()方法可以对字符串进行截取。
substring()方法被两种不同的方法重载,来满足不同的需求。
(1)substring(int beginIndex)
该方法返回的是从指定的索引位置开始截取直到该字符串结尾的子串。

源码如下:

public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}

语法如下:

str.substring(int beginIndex);

其中,beginIndex指定从某一索引处开始截取字符串。
(2)substring(int beginIndex, int endIndex)
该方法返回的是从字符串某一索引位置开始截取到某一索引位置结束的子串。

源码如下:

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}

语法如下:

 substring(int beginIndex, int endIndex);

五、replace()方法

replace()方法可以实现将指定的字符或字符串替换成新的字符或字符串。
源码如下:

public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}

语法如下:

str.replace(char oldChar,char newChar);

oldChar:要替换的字符或字符串。
newChar:用于替换的字符或字符串的内容。
replace()方法返回的结果是一个新的字符串。如果字符串oldChar没有出现在该对象表达式中的字符串序列中,则将原字符串返回。

六、length()方法

使用String类的length()方法可以获取声明的字符串对象的长度。
源码如下:

public int length() {
return value.length;
}
/**
* Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
*
* @return {@code true} if {@link #length()} is {@code 0}, otherwise
* {@code false}
*
* @since 1.6
*/

语法如下:

str.length();

七、indexOf()方法

该方法用于返回参数字符串s在指定字符串中首次出现的索引位置。
源码如下:
public int indexOf(String str) {
return indexOf(str, 0);
}

/**
 * Returns the index within this string of the first occurrence of the
 * specified substring, starting at the specified index.
 *
 * <p>The returned index is the smallest value <i>k</i> for which:
 * <blockquote><pre>
 * <i>k</i> &gt;= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
 * </pre></blockquote>
 * If no such value of <i>k</i> exists, then {@code -1} is returned.
 *
 * @param   str         the substring to search for.
 * @param   fromIndex   the index from which to start the search.
 * @return  the index of the first occurrence of the specified substring,
 *          starting at the specified index,
 *          or {@code -1} if there is no such occurrence.
 */

语法如下:

str.indexOf(substr)

substr:要搜索的字符串。

八、lastIndexOf()方法

该方法用于返回参数字符串s在指定字符串中最后一次出现的索引位置。
源码如下:
public int lastIndexOf(String str) {
return lastIndexOf(str, value.length);
}

/**
 * Returns the index within this string of the last occurrence of the
 * specified substring, searching backward starting at the specified index.
 *
 * <p>The returned index is the largest value <i>k</i> for which:
 * <blockquote><pre>
 * <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>)
 * </pre></blockquote>
 * If no such value of <i>k</i> exists, then {@code -1} is returned.
 *
 * @param   str         the substring to search for.
 * @param   fromIndex   the index to start the search from.
 * @return  the index of the last occurrence of the specified substring,
 *          searching backward from the specified index,
 *          or {@code -1} if there is no such occurrence.
 */

语法如下:

str.lastIndexOf(substr)

substr:要搜索的字符串。

九、charAt()方法

使用charAt()方法可把指定索引处的字符返回。
源码如下:

public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}

语法如下:

str.charAt(int index);

index:整型值,用于指定要返回字符的下标。

十、trim()方法

trim方法去除空格,返回字符串的副本,忽略前导空格和尾部空格。
源码如下:

public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ’ ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ’ ')) {
len–;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

语法如下:

str.trim();

到这里这篇博客要介绍的内容已经讲完了,后续可能会再添加几种String的类方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值