字符串常用方法


1.字符串的連接

  public String concat(String str) 

將參數str添加到調用的字符串后面

eg.

String a= "abc";
String b="egd";
String string=a.concat(b);
System.out.println(string);//結果為abcegd

 

2.字符串的長度

public int length()

計算調用此方法的字符串長度

eg.

String a= "abc";
int alength=a.length();
System.out.println(alength);//結果為3

 

3.字符在字符串所在的位置

 public char charAt(int index) 

獲得字符串指定位置的字符,索引值從0開始到length()-1

eg.

String a= "abcdedjf";
char b = a.charAt(0);
System.out.println(b);//結果為a

 

4.截取字符串

public String substring(int beginIndex)

public String substring(int beginIndex, int endIndex) 

截取需要的字符串,兩個方法的索引值都是從0開始

第二種方法是從beginIndex截取到endIndex,截取結果包括beginIndex對應的字符,但不包括iendIndex對應的字符

eg.

String a= "abcdedjf";
String b = a.substring(0, 3);
System.out.println(b);//結果為abc

eg.

String a= "abcdedjf";
String b = a.substring(4, 6);
System.out.println(b);//結果為ed

 

5.字符串的比較

    public boolean equals(Object anObject)

比較兩個字符串是否相等,這個方法涉及到hashCode()方法,關於這兩個方法的區別,請參考:

https://www.cnblogs.com/jesonjason/p/5492208.html

 

eg.

String a= "abcdedjf";
String b=new String("abcdedjf");
System.out.println(a.equals(b));//結果為true

 

6.查找字符,字符串在字符串中的位置

public int indexOf(int ch)

public int indexOf(String str)

public int indexOf(int ch, int fromIndex)

public int lastIndexOf(int ch)

第一個方法是返回查找字符ch所在的索引值,如果有多個匹配,則會匹配查找第一個字符,返回其索引值

第二個方法是返回查找字符串str所在的索引值,如果有多個匹配,則會匹配查找第一個字符,返回其索引值

第三個方法是字符ch在字符串fromindex位后出現的第一個位置,沒有找到返加-1

第四個方法是從后往前返回查找字符ch所在的索引值,如果有多個匹配,則會匹配查找到的第一個字符,返回其索引值

eg.

String a = "abcdedjfa";
int charindex = a.indexOf('a');
System.out.println(charindex);//結果為0
int stringIndex = a.indexOf("cd");
System.out.println(stringIndex);//結果為2
int index = a.indexOf('a', 5);
System.out.println(index);//結果為8
int lastIndex = a.lastIndexOf('a');
System.out.println(lastIndex);//結果為8

 

 7.去除字符串中的空格

public String trim()

public String replace(CharSequence target, CharSequence replacement)

第一個方法能去除字符串前后的空格,但去除不了字符串中間的空格

第二個方法可以替換包括首尾和中間的空格

 eg.

String a = " abcde djfa ";
String aString = a.trim();
System.out.println(aString);//結果為abcde djfa

 

eg.

String a = " abcde djfa ";
String aString = a.replace(" ", "");
System.out.println(aString);//結果為abcdedjfa

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM