Thinking in java第8天

第13章 字符串

  1. String的不變性
  2. Java不允許程序員重載任何操作符,String中的+和+=是僅有的兩個重載過的操作符,當使用+來合併字符串時,JVM會自動優化使用StringBuilder
  3. StringBuilder/StringBuffer
    • 兩者都是可以改變的
    • StringBuilder是線程不安全的執行效率會較高,而StringBuffer是線程安全的
    • 實例化時不傳入長度,會默認實例化長度是16字符的數組
    • 常用的方法如:inser(),repleace(),substring(),reverse(),append(),tostring(),delete()
  4. 在覆寫toString時容易照成遞歸
    • public class InfiniteRecurison {
      	public String toString() {
      //		return " InifiniteRecurison address: " + this;//this會自動調用自己的toString()方法
      		return " InifiniteRecurison address: " + super.toString();
      	}
      	
      	@Test
      	public void test(){
      		List<InfiniteRecurison> v = new ArrayList<InfiniteRecurison>();
      		for(int i=0;i<10;i++){
      			v.add(new InfiniteRecurison());
      		}
      		System.out.println(v);
      	}
      }
      
  5. String 上的操作都是返回一個新的String對象,同時,如果內容沒有發生改變,則返回原先對象的引用(以下列一些方法,其他的可以去看源碼)
    • valueOf():返回一個表示參數內容的String,如果valueOf(true)則返回“true”字符串
    • intern():返回字符串對象的規範化表示形式。一個初始爲空的字符串池,它由類 String 私有地維護。當調用 intern 方法時,如果池已經包含一個等於此String 對象的字符串(用equals(Object) 方法確定),則返回池中的字符串。否則,將此String 對象添加到池中,並返回此String 對象的引用。
  6. 格式化輸出:Formatter類
    • Formatter類輸出時默認情況下是右對齊的,可以使用 - 來該表方向
    • width:控制一個域的尺寸
    • precise:
      • 應用於String:表示輸出字符的最大數量
      • 應用於浮點數:表示小數部分要顯示出來的位數(默認是6位)
      • 應用於整數:報異常
    • 類型轉換字符:值得注意的是當想把0用%b轉換時是返回的true
    • String.format()是一個static方法,它接受有Formatter.format()一樣的參數,但是隻返回String
  7. 正則表達式(僅限Java)
    • \\在Java和其他語言中的不同含義
      • 其他語言:我想要在正則表達式中插入一個普通的反斜槓,請不要給他任何特殊的含義
      • Java中:我要插入一個正則表達式的反斜槓,所以其後的字符具有特殊的含義:如,一位數字\\d,想插入一個普通的反斜槓\\\\,不過如換行和製表符只需要單反斜槓\n\t...
    • ‘+’:一個或者多個之前的表達式 [-?:表示零個或者一個-號]
    • ‘?’:零個或者一個
    • 括號有着將表達式分組的效果
    • '|':則表示或操作[(-|\\+)?:表示零個或者一個-或+]
    • '\W'表示非單詞字符;'\w'表示一個單詞字符
    • String類
      • 內建正則
      • split()
        • 與正則表達式匹配的部分,在最終的結果中都不存在
        • 重載版本允許限制字符串分割的次數
      • 替換
        • 允許只替換表達式的第一個匹配的子串(replaceFirst()),也可以替換所有匹配的子串(replaceAll())
    • 字符:
      • B:指定字符B
      • \xhh:十六進制值爲0xhh的字符
      • \uhhhh:十六進制爲0xhhhh的字符
      • \t:製表符;\n:換行符;\r:回車;\f:換頁;\e:轉義
    • 字符類:
      • .:任意字符
      • [abc]:包含a,b,c的任意字符和[a|b|c]相同
      • [^abc]:除了a,b,c之外的任意字符
      • [a-zA-Z]:從a-z,A-Z的任意字符
      • [abc[hij]]:任意a,b,c,h,i,j的字符和[a|b|c|h|i|j]相同
      • [a-z&&[hij]]:任意h,i,j(交)
      • \s:空白符;\S:非空白符
      • \d:數字[0-9];\D:非數字[^0-9]
      • \w:詞字數[a-zA-Z0-9];\W:非詞數字[^\w]
    • /*
       * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
       * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
       */
      
      package java.lang;
      
      
      /**
       * A <tt>CharSequence</tt> is a readable sequence of <code>char</code> values. This
       * interface provides uniform, read-only access to many different kinds of
       * <code>char</code> sequences.
       * A <code>char</code> value represents a character in the <i>Basic
       * Multilingual Plane (BMP)</i> or a surrogate. Refer to <a
       * href="Character.html#unicode">Unicode Character Representation</a> for details.
       *
       * <p> This interface does not refine the general contracts of the {@link
       * java.lang.Object#equals(java.lang.Object) equals} and {@link
       * java.lang.Object#hashCode() hashCode} methods.  The result of comparing two
       * objects that implement <tt>CharSequence</tt> is therefore, in general,
       * undefined.  Each object may be implemented by a different class, and there
       * is no guarantee that each class will be capable of testing its instances
       * for equality with those of the other.  It is therefore inappropriate to use
       * arbitrary <tt>CharSequence</tt> instances as elements in a set or as keys in
       * a map. </p>
       *
       * @author Mike McCloskey
       * @since 1.4
       * @spec JSR-51
       */
      
      public interface CharSequence {
      
          /**
           * Returns the length of this character sequence.  The length is the number
           * of 16-bit <code>char</code>s in the sequence.</p>
           *
           * @return  the number of <code>char</code>s in this sequence
           */
          int length();
      
          /**
           * Returns the <code>char</code> value at the specified index.  An index ranges from zero
           * to <tt>length() - 1</tt>.  The first <code>char</code> value of the sequence is at
           * index zero, the next at index one, and so on, as for array
           * indexing. </p>
           *
           * <p>If the <code>char</code> value specified by the index is a
           * <a href="{@docRoot}/java/lang/Character.html#unicode">surrogate</a>, the surrogate
           * value is returned.
           *
           * @param   index   the index of the <code>char</code> value to be returned
           *
           * @return  the specified <code>char</code> value
           *
           * @throws  IndexOutOfBoundsException
           *          if the <tt>index</tt> argument is negative or not less than
           *          <tt>length()</tt>
           */
          char charAt(int index);
      
          /**
           * Returns a new <code>CharSequence</code> that is a subsequence of this sequence.
           * The subsequence starts with the <code>char</code> value at the specified index and
           * ends with the <code>char</code> value at index <tt>end - 1</tt>.  The length
           * (in <code>char</code>s) of the
           * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>
           * then an empty sequence is returned. </p>
           *
           * @param   start   the start index, inclusive
           * @param   end     the end index, exclusive
           *
           * @return  the specified subsequence
           *
           * @throws  IndexOutOfBoundsException
           *          if <tt>start</tt> or <tt>end</tt> are negative,
           *          if <tt>end</tt> is greater than <tt>length()</tt>,
           *          or if <tt>start</tt> is greater than <tt>end</tt>
           */
          CharSequence subSequence(int start, int end);
      
          /**
           * Returns a string containing the characters in this sequence in the same
           * order as this sequence.  The length of the string will be the length of
           * this sequence. </p>
           *
           * @return  a string consisting of exactly this sequence of characters
           */
          public String toString();
      
      }
    • Pattern和Matcher
      • Pattern.compile():編譯正則表達式串生成Matcher對象
      • Matcher.find():可以用來在CharSequence中查找多個匹配,可以利用該重載方法選取搜索的起始位置
        • Matcher.lonkingAt()和Matcher.matches()都可以匹配字符串,但是區別在於:1.這兩個都必須在正則表達式與輸入的最開始處就開始匹配時纔會成功
        • 2.而matches只有在整個輸入都匹配正則表達式時纔會成功
      • Matcher.group():
        • 組是用括號劃分的正則表達式,可以根據組的編號來引用某個組
        • groupCount()
        • group()
        • group(int)
        • start(int group)
        • end(int group)
      • Matcher.start()/Matcher.end()
      • Matcher.reset():將現有的Matcher對象用於一個新的字符序列
  8. Scanner:具有多個不同的方法,可以讀取串,整數等等,還有hasNext()方法判斷是否有下一個詞
    • Scanner在讀取的時候默認是有空白字符對輸入進行分詞
    • 我們可以使用uerDelemiter(Pattern)方法指定分詞的定界符
  9. 可以使用正則表達式來掃描複雜數據,如日誌
    • public class ThreatAnalyzer {
      	static String threatFile = 
      			"58.27.82.161@02/10/2005\n" +
      					"58.27.82.161@02/10/2005\n" +
      					"58.27.82.161@02/10/2005\n" +
      					"58.27.82.161@02/10/2005\n" +
      					"58.27.82.161@02/10/2005\n" +
      			"204.45.234.40@20/11/2005";
      	public static void main(String[] args) {
      		Scanner scanner = new Scanner(threatFile);
      		String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{2}/\\d{2}/\\d{4})";
      		while(scanner.hasNext(pattern)){
      			scanner.next(pattern);
      			MatchResult result = scanner.match();
      			String ip = result.group(1);
      			String date = result.group(2);
      			System.out.println("IP: "+ip+"; Date: "+date);
      		}
      	}
      }
      


  10. StringTokenizer類
發佈了28 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章