歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中的字符串

Java中的字符串

日期:2017/3/1 9:10:14   编辑:Linux編程

Java語言中,把字符串作為對象來處理,類String就可以用來表示字符串(類名首字母都是大寫的)。

1.字符串常量

  字符串常量是用雙引號括住的一串字符。

例如:"Hello World"

2.String表示字符串變量

  String用來可以創建字符串對象,String使用示例:

1 String s=new String() ;   //生成一個空串 
2 String s1="Hello World"; //聲明s1為字符串"Hello World"的引用

3. 字符串 判斷相等的方法String.equals()

  在Java中判等是有講究的,往往直接使用==得出的答案可能是正確的也可能是錯誤的,看這段示例:

  

1  String s1="a";
2  String s2="a";
3  s1+="b";
4  System.out.println(s1=="ab");         // false
5  System.out.println(s1==s2+"b");     // false
6  System.out.println(s2=="a");           // true
7  System.out.println(s1.equals("ab")); // true
8 System.put.println(new String("ab")==new String("ab")); // false

  看了這段代碼,你可能會明白了。==判斷不僅判斷內存地址中的內容是不是相等,還要判斷引用的地址是不是相等;而equals()方法則是用來判斷內容相等的,這下明白了吧?

  還有以下幾點需要注意的地方:

    • 在Java中,內容相同的字串常量(“a”)只保存一份以節約內存,所以s1,s2實際上引用的是同一個對象。
    • 編譯器在編譯s1一句時,會去掉“+”號,直接把兩個字串連接起來得一個字串(“ab”)。這種優化工作由Java編譯器自動完成。
    • 當直接使用new關鍵字創建字符串對象時,雖然值一致(都是“ab”),但仍然是兩個獨立的對象。

4、訪問字符串

類String中提供了length( )、charAt( )、indexOf( )、lastIndexOf( )、getChars( )、getBytes( )、toCharArray( )等方法。

  1. public int length() 此方法返回字符串的字符個數
  2. public char charAt(int index) 此方法返回字符串中index位置上的字符,其中index 值的 范圍是0~length-1
  3. public int indexOf(int ch)
  4. public lastIndexOf(in ch)

返回字符ch在字符串中出現的第一個和最後一個的位置

  1. public int indexOf(String str)
  2. public int lastIndexOf(String str)

返回子串str中第一個字符在字符串中出現的第一個和最後一個的位置

  1. public int indexOf(int ch,int fromIndex)
  2. public lastIndexOf(in ch ,int fromIndex)

返回字符ch在字符串中位置fromIndex以後出現的第一個和最後一個的位置

  1. public int indexOf(String str,int fromIndex)
  2. public int lastIndexOf(String str,int fromIndex)

返回子串str中的第一個字符在字符串中位置fromIndex後出現的第一個和最後一個的位置。

  1. public void getchars(int srcbegin,int end ,char buf[],int dstbegin)

srcbegin 為要提取的第一個字符在源串中的位置, end為要提取的最後一個字符在源串中的位置,字符數組buf[]存放目的字符串,dstbegin 為提取的字符串在目的串中的起始位置。

  1. public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin)

參數及用法同上,只是串中的字符均用8位表示。

5、修改字符串

修改字符串的目的是為了得到新的字符串,有關各個方法的使用,參考java API。

String類提供的方法:

    • concat( )
    • replace( )
    • substring( )
    • toLowerCase( )
    • toUpperCase( )
  1. public String contat(String str);

用來將當前字符串對象與給定字符串str連接起來。

  1. public String replace(char oldChar,char newChar);

用來把串中出現的所有特定字符替換成指定字符以生成新串。

  1. public String substring(int beginIndex);
  2. public String substring(int beginIndex,int endIndex);

用來得到字符串中指定范圍內的子串。

  1. public String toLowerCase();

把串中所有的字符變成小寫。

  1. public String toUpperCase();

把串中所有的字符變成大寫。

Copyright © Linux教程網 All Rights Reserved