您的位置:首页 > 编程语言 > Java开发

54-55_数组_String类的常用方法_JDK源码分析_内存分析

2017-06-09 15:30 543 查看

String

String 类对象保存不可修改的Unicode字符序列

String类的下述方法能创建并返回一个新的String对象: concat, replace,  substring, toLowerCase, toUpperCase, trim.

提供查找功能的有关方法: endsWith, startsWith, indexOf,,lastIndexOf.

提供比较功能的方法: equals, equalsIgnoreCase, compareTo.

其它方法: charAt, length.

public static String valueOf(…)可以将基本类型数据转换为字符串。


课堂代码:

/**
* String:不可变字符序列!
* 三个作业:
* 1. 练习String类的常用方法
* 2. 结合数组查看源码
* 3. 提高:按照老师的方法将String类中相关方法的源码看一看。
* @author dell
*
*/
public class TestString {
public static void main(String[] args) {
String str = new String("abcd");
String str2 = new String("abcd");
System.out.println(str2.equals(str));//比较内容是否相等。
System.out.println(str2==str);//比较是否是同一个对象
System.out.println(str.charAt(2));//返回第二个字符

String str3 = "def";
String str4 = "def";
System.out.println(str3.equals(str4));
System.out.println(str3==str4);//都在常量池,属于同一个对象

System.out.println(str3.indexOf('y'));
String s = str3.substring(0);
System.out.println(s);
String str5 = str3.replace('e', '*');
System.out.println(str5);

String str6 = "abcde,rrtt,cccee";
String[] strArray = str6.split(",");
for(int i=0;i<strArray.length;i++){
System.out.println(strArray[i]);
}
String str7 = "  aa  bb  ";
String str77 = str7.trim();
System.out.println(str77.length());

System.out.println("Abc".equalsIgnoreCase("abc"));
System.out.println("Abcbd".indexOf('b'));
System.out.println("Abcbd".lastIndexOf('b'));
System.out.println("Abcbd".startsWith("Ab"));
System.out.println("Abcbd".endsWith("bd"));
System.out.println("Abcbd".toLowerCase());
System.out.println("Abcbd".toUpperCase());

System.out.println("##################");
String gh = new String("a");
for (int i = 0; i < 1000; i++) {
gh = gh + i;
}
System.out.println(gh);
}

}


java中String的常用方法

1、length() 字符串的长度

length和length()的区别:

length是字符数组的属性

length()是String类的一个方法,返回字符数组value的length

int length() {
return value.length;
}
char chars[]={'a','b'.'c'};
String s=new String(chars);
int len=s.length();


2、charAt() 截取一个字符

char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
char ch;
ch="abc".charAt(1); 返回'b'


3、 getChars() 截取多个字符

void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
  //srcBegin指定了子串开始字符的下标,srcEnd指定了子串结束后的下一个字符的下标。因此,子串包含从srcBegin到srcEnd的字符。接收字符的数组由dst指定,dst中开始复制子串的下标值是dstBegin。
String s="this is a demo of the getChars method.";
char buf[]=new char[20];
s.getChars(10,14,buf,0);


4、getBytes()

替代getChars()的一种方法是将字符存储在字节数组中,该方法即getBytes()。(已被遗弃)

5、toCharArray()

将此实例中的字符复制到 Unicode 字符数组。

char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}


6、equals()和equalsIgnoreCase() 比较两个字符串

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;
}

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


7、regionMatches()

用于比较一个字符串中特定区域与另一特定区域,它有一个重载的形式允许在比较中忽略大小写。

public boolean regionMatches(int toffset, String other, int ooffset,int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}


8、startsWith()和endsWith()  

startsWith()方法决定是否以特定字符串开始,endWith()方法决定是否以特定字符串结束

public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}

public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}

public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}


9、equals()和==

equals()方法比较字符串对象中的字符,

==运算符比较两个对象是否引用同一实例。

String s1="Hello";
String s2=new String(s1);
s1.eauals(s2); //true
s1==s2;//false


10、compareTo()和compareToIgnoreCase()

比较字符串:如果参数字符串等于此字符串,则返回 0 值;如果按字典顺序此字符串小于字符串参数,则返回一个小于 0 的值;如果按字典顺序此字符串大于字符串参数,则返回一个大于 0 的值。

public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;

int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}

public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}

String query = new String();
String number = new String();
int i = 0;
query = "a";
number = "1";
i = query.compareTo("A"); (a在A之后,返回大于0的值)
i = number.compareTo("2"); (1在2之前,返回小于0的值)


11、indexOf()和lastIndexOf()

  indexOf() 查找字符或者子串第一次出现的地方。

  lastIndexOf() 查找字符或者子串是后一次出现的地方。

static int indexOf(char[] source, int sourceOffset, int sourceCount,char[] target, int targetOffset, int targetCount,int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}

char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);

for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}

/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);

if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}

if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}

static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
/*
* Check arguments; return immediately where possible. For
* consistency, don't check for null str.
*/
int rightIndex = sourceCount - targetCount;
if (fromIndex < 0) {
return -1;
}
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
/* Empty string always matches. */
if (targetCount == 0) {
return fromIndex;
}

int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];
int min = sourceOffset + targetCount - 1;
int i = min + fromIndex;

startSearchForLastChar:
while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;

while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
}

public int lastIndexOf(int ch, int fromIndex) {
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
int i = Math.min(fromIndex, value.length - 1);
for (; i >= 0; i--) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return lastIndexOfSupplementary(ch, fromIndex);
}
}


12、substring()截取子串 

它有两种形式,第一种是:String substring(int startIndex)

第二种是:String substring(int startIndex,int endIndex)

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);
}

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);
}


13、concat() 连接两个字符串

将指定字符串连接到此字符串的结尾。

如果参数字符串的长度为 0,则返回此 String 对象。否则,创建一个新的 String 对象,用来表示由此 String 对象表示的字符序列和参数字符串表示的字符序列连接而成的字符序列.

public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}


14 、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;
}
//例如:String s="Hello".replace('l','w');


第二种形式是用一个字符序列替换另一个字符序列,形式如下:

public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}


15、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;
}


16、valueOf() 转换为字符串

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

public static String valueOf(char data[]) {
return new String(data);
}

public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}

public static String valueOf(boolean b) {
return b ? "true" : "false";
}

public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}

public static String valueOf(int i) {
return Integer.toString(i);
}


17、toLowerCase() 转换为小写

18、toUpperCase() 转换为大写

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: