1. 程式人生 > >java String類的用法 Java String類的練習和常用方法

java String類的用法 Java String類的練習和常用方法

Java String類的練習和常用方法

2016年12月01日 11:22:04 閱讀數:989
													<span class="tags-box artic-tag-box">
							<span class="label">標籤:</span>
															<a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;java&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=java&amp;t=blog" target="_blank">java																</a><a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;string&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=string&amp;t=blog" target="_blank">string																</a><a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;class&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=class&amp;t=blog" target="_blank">class																</a>
						<span class="article_info_click">更多</span></span>
																				<div class="tags-box space">
							<span class="label">個人分類:</span>
															<a class="tag-link" href="https://blog.csdn.net/ss19497/article/category/6550240" target="_blank">JAVA知識點																</a>
						</div>
																							</div>
			<div class="operating">
													</div>
		</div>
	</div>
</div>
<article class="baidu_pl">
	<div id="article_content" class="article_content clearfix csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post">
							<div class="article-copyright">
				版權宣告:本文為博主原創文章,未經博主允許不得轉載。					https://blog.csdn.net/ss19497/article/details/53419520				</div>
							            <div id="content_views" class="markdown_views">
						<!-- flowchart 箭頭圖示 勿刪 -->
						<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
						<p>第一個比較常用的string類中的.length( );該方法求字串中的長度/下面我們舉個例子</p>
public class Test {
    public static void main(String[] args) {
        String str1 = "www.csdn.net";
        int a = str1.length();
        System.out.println("部落格網址長度 : " + a);//輸出12
    }
}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

求字串中某一個字元的位置用.charAt( );只能傳入一個引數!

public
static void main(String[] args) { String str1 = "ABCDEFG"; char a = str1.charAt(3);//傳入引數 System.out.println(a);//輸出結果為D +1 }
  • 1
  • 2
  • 3
  • 4
  • 5

擷取字串用string類的.substring( );

public static void main(String[] args) {
        String str = "Hello,Word!";
        String str1 = str.substring(6
,10);//擷取6—10位 System.out.println(str1);//輸出結果為word }//注:如果只傳入一個引數的話會擷取該引數之後的全部內容!
  • 1
  • 2
  • 3
  • 4
  • 5

字串比較 .compareTo( );邏輯比較.equals( );

public static void main(String[] args) {
        String str1 = "ABC";
        String str2 = "DEF";

        int a = str1.compareTo(str2);
        int b = str2.compareTo(str1);

        boolean c = str1.equals(str2);
        boolean d = str2.equals(str2);

        System.out.println(a);//-3
        System.out.println(b);//3
        //如果字串str1和str2相同則a b 結果為0
        System.out.println(c);//false
        System.out.println(d);//true
        //.equals 相同返回true 不同返回false
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

字串拼接也叫做字串連線.concat

public static void main(String[] args) {
        String str = "He".concat("ll").concat("o");
        System.out.println(str);//輸出Hello
    }
  
  • 1
  • 2
  • 3
  • 4

單字串查詢.indexOf( ); 從左開始查詢,沒有該字元返回-1
.println( );從尾部開始查詢 但計數還是從頭開始

public static void main(String[] args) {

    String str = new String("I am a good student");
    int a = str.indexOf('a');
    int b = str.indexOf("good");
    int c = str.indexOf("w",2);

    int d = str.lastIndexOf('a');
    int e = str.lastIndexOf("a",3);

    System.out.println(a);//2 空格也是字元
    System.out.println(b);//7 只能查詢單字元
    System.out.println(c);//-1 沒有的返回-1

    System.out.println(d);//5 從尾部查詢
    System.out.println(e);//2
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

將字串大小寫轉換
.toLowerCase( );轉換小寫字元
.toUpperCase( );轉換大寫字元

public static void main(String[] args) {

        String str = "Hello Word";
        String str1 = str.toLowerCase();
        String str2 = str.toUpperCase();

        System.out.println(str1);//hello word
        System.out.println(str2);//HELLO WORD
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

字元替換
.replace( , );

public static void main(String[] args) {

        String str = "Hello Word";
        String str1 = str.replace('e', 'H');
        String str2 = str.replace("Hello", "Word");
        System.out.println(str1);//將e替換成H 輸出HHllo Word
        System.out.println(str2);//同上 輸出Word Word

    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

.replaceAll(” “, ” “); 替換所有的字元
.replaceFirst(” “, ” “);替換第一個

public static void main(String[] args) {

        String str = new String("asdzxcasd");

        String str3 = str.replaceFirst("asd", "fgh");
        String str4 = str.replaceAll("asd", "fgh");

        System.out.println(str3);//fghzxcasd
        System.out.println(str4);//fghzxcfgh
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

擷取字串兩端的空格.trim( );

public static void main(String[] args) {

        String str = new String(" Hello  ");
        String str1 = str.trim();
        int a = str.length();//a是沒擷取的
        int b = str1.length();//b是擷取空格過度

        System.out.println(str1);//擷取空格輸出Hello
        System.out.println(a);//求一下長度結果是8
        System.out.println(b);//擷取後的長度是5 有三個空格
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

判斷字串是否與頭部和尾部相同
.startsWith(” “); 判斷頭部分
.endsWith(” “);判斷尾部分

public static void main(String[] args) {

        String str = new String("asdfgh");
        boolean a = str.startsWith("as");
        boolean b = str.startsWith("sd");

        boolean c = str.endsWith("gh");
        boolean d = str.endsWith("hg");

        System.out.println(a);//頭部相同返回true
        System.out.println(b);//不相同返回false
        System.out.println(c);//尾部相同返回true
        System.out.println(d);//不相同返回false
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

判斷字元是否包含在字串中.contains(” “);

public static void main(String[] args) {

        String str = new String("Welcome");
        boolean a = str.contains("lc");
        boolean b = str.contains("ok");

        System.out.println(a);//有此字元返回true
        System.out.println(b);//沒有次字元輸出false
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

字串分割符.split

public static void main(String[] args) {

        String[] a = "aa\\bb\\cc".split("\\*");
        for (int i = 0; i < a.length; i++) {
            System.out.print("--" + a[i]);
        }//輸出--aa\bb\cc
    }
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

版權所有 侵版必究!轉載註明出處!

下面附string所有方法和說明

String 方法

下面是 String 類支援的方法,更多詳細,參看 Java String API 文件:

SN(序號)

方法描述

1 char charAt(int index)
返回指定索引處的 char 值。
2 int compareTo(Object o)
把這個字串和另一個物件比較。
3 int compareTo(String anotherString)
按字典順序比較兩個字串。
4 int compareToIgnoreCase(String str)
按字典順序比較兩個字串,不考慮大小寫。
5 String concat(String str)
將指定字串連線到此字串的結尾。
6 boolean contentEquals(StringBuffer sb)
當且僅當字串與指定的StringButter有相同順序的字元時候返回真。
7 static String copyValueOf(char[] data)
返回指定陣列中表示該字元序列的 String。
8 static String copyValueOf(char[] data, int offset, int count)
返回指定陣列中表示該字元序列的 String。
9 boolean endsWith(String suffix)
測試此字串是否以指定的字尾結束。
10 boolean equals(Object anObject)
將此字串與指定的物件比較。
11 boolean equalsIgnoreCase(String anotherString)
將此 String 與另一個 String 比較,不考慮大小寫。
12 byte[] getBytes()
使用平臺的預設字符集將此 String 編碼為 byte 序列,並將結果儲存到一個新的 byte 陣列中。
13 byte[] getBytes(String charsetName)
使用指定的字符集將此 String 編碼為 byte 序列,並將結果儲存到一個新的 byte 陣列中。
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
將字元從此字串複製到目標字元陣列。
15 int hashCode()
返回此字串的雜湊碼。
16 int indexOf(int ch)
返回指定字元在此字串中第一次出現處的索引。
17 int indexOf(int ch, int fromIndex)
返回在此字串中第一次出現指定字元處的索引,從指定的索引開始搜尋。
18 int indexOf(String str)
返回指定子字串在此字串中第一次出現處的索引。
19 int indexOf(String str, int fromIndex)
返回指定子字串在此字串中第一次出現處的索引,從指定的索引開始。
20 String intern()
返回字串物件的規範化表示形式。
21 int lastIndexOf(int ch)
返回指定字元在此字串中最後一次出現處的索引。
22 int lastIndexOf(int ch, int fromIndex)
返回指定字元在此字串中最後一次出現處的索引,從指定的索引處開始進行反向搜尋。
23 int lastIndexOf(String str)
返回指定子字串在此字串中最右邊出現處的索引。
24 int lastIndexOf(String str, int fromIndex)
返回指定子字串在此字串中最後一次出現處的索引,從指定的索引開始反向搜尋。
25 int length()
返回此字串的長度。
26 boolean matches(String regex)
告知此字串是否匹配給定的正則表示式。
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
測試兩個字串區域是否相等。
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
測試兩個字串區域是否相等。
29 String replace(char oldChar, char newChar)
返回一個新的字串,它是通過用 newChar 替換此字串中出現的所有 oldChar 得到的。
30 String replaceAll(String regex, String replacement
使用給定的 replacement 替換此字串所有匹配給定的正則表示式的子字串。
31 String replaceFirst(String regex, String replacement)
使用給定的 replacement 替換此字串匹配給定的正則表示式的第一個子字串。
32 String[] split(String regex)
根據給定正則表示式的匹配拆分此字串。
33 String[] split(String regex, int limit)
根據匹配給定的正則表示式來拆分此字串。
34 boolean startsWith(String prefix)
測試此字串是否以指定的字首開始。
35 boolean startsWith(String prefix, int toffset)
測試此字串從指定索引開始的子字串是否以指定字首開始。
36 CharSequence subSequence(int beginIndex, int endIndex)
返回一個新的字元序列,它是此序列的一個子序列。
37 String substring(int beginIndex)
返回一個新的字串,它是此字串的一個子字串。
38 String substring(int beginIndex, int endIndex)
返回一個新字串,它是此字串的一個子字串。
39 char[] toCharArray()
將此字串轉換為一個新的字元陣列。
40 String toLowerCase()
使用預設語言環境的規則將此 String 中的所有字元都轉換為小寫。
41 String toLowerCase(Locale locale)
使用給定 Locale 的規則將此 String 中的所有字元都轉換為小寫。
42 String toString()
返回此物件本身(它已經是一個字串!)。
43 String toUpperCase()
使用預設語言環境的規則將此 String 中的所有字元都轉換為大寫。
44 String toUpperCase(Locale locale)
使用給定 Locale 的規則將此 String 中的所有字元都轉換為大寫。
45 String trim()
返回字串的副本,忽略前導空白和尾部空白。
46 static String valueOf(primitive data type x)
返回給定data type型別x引數的字串表示形式。

聯絡作者:[email protected]

				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									if(typeof window.localStorage === "object" && typeof window.csdn.anonymousUserLimit === "object"){
										if(!window.csdn.anonymousUserLimit.judgment()){
											window.csdn.anonymousUserLimit.Jumplogin();
											return false;
										}else if(!currentUserName){
											window.csdn.anonymousUserLimit.updata();
										}
									}
									
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>