天天看點

JAVA基礎 - 關于String字元串的一些方法

/**
 * 字元串的複制
 * 字元串的比較 - compareTo()   equalsIgnoreCase()
 * 查找字元串中是否包含某個字元 - indexOf()
 * 字元串的截取  - substring()
 * 字元串替換 - replace
 * 判斷某字元串是否以指定字元串開始或結尾 - startsWith()  endsWith()
 * 轉換字元串大小寫 - toUpperCase()  toLowerCase()
 * 
 * @author LXL 2017年4月1日
 */
public class StringAndChar {

	public static void main(String[] args) {

		char[] a = { 'a', 's', 'd', 'f' };

		String str = new String(a);
		//		String str2 = a; // 這句會報錯. 因為類型不一樣
		System.out.println("str = " + str); // str = asdf
		String str1 = "aaaa";
		String str2 = "aaaa";
		String str3 = "ASDF";

		/**
		 * 字元串的比較 - compareTo()
		 * 按字典順序比較兩個字元串. 基于字元串中各個字元的Unicode值
		 */
		System.out.println("str.compareTo(str1) --- " + str.compareTo(str1)); // 18

		/**
		 * 字元串的相等
		 * equals()
		 * equalsIgnoreCase() 不區分大小寫
		 */
		// equals()
		System.out.println("str.equals(str1) --- " + str.equals(str1)); // false
		System.out.println("str2.equals(str1) --- " + str2.equals(str1)); // true

		// equalsIgnoreCase() 不區分大小寫
		System.out.println("str.equalsIgnoreCase(str3) --- " + str.equalsIgnoreCase(str3)); // true

		/**
		 * indexOf() : 查找字元串中是否包含某個字元
		 */
		String email = "[email protected]@";
		int index = email.indexOf("@");
		if (index != -1) {
			System.out.println(email + "  郵箱正确   " + "index --- " + index); // 郵箱正确   index --- 3
		} else {
			System.out.println(email + "  郵箱不正确   " + "index --- " + index); // 如果把兩個@都去掉,列印為: 郵箱不正确 index --- -1
		}

		/**
		 * 字元串的截取  - str.substring(i)  str.substring(beginIndex, endIndex)
		 * str.substring(i) : 從index = i的位置開始顯示 . i位置的字元也顯示
		 * str.substring(beginIndex, endIndex) : 從begin的位置開始顯示, 到end的位置結束, begin位置的字元顯示, end位置的不顯示
		 */
		String s_substring = "helloworld";
		System.out.println(s_substring + ".substring(3) = " + s_substring.substring(3)); // loworld
		System.out.println(s_substring + ".substring(2, 6) = " + s_substring.substring(2, 6)); // llow

		/**
		 * 字元串替換 - replace(oldChar, newChar) : 使用後原字元串不發生改變
		 */
		String replace1 = "ABCDEFG";
		String replace2 = replace1.replace('C', 'Z');
		System.out.println(replace1 + "  " + replace2); // ABCDEFG  ABZDEFG

		/**
		 * 判斷某字元串是否以指定字元串開始或結尾
		 * startsWith()  endsWith()
		 */
		String id = "130406000000000000";
		if (id.startsWith("130")) { // 以開頭為河北省
			System.out.print("河北省, ");
		}
		for (int i = 0; i < 10; i++, i++) {
			if (id.endsWith(i + "")) { // 以尾号判斷性别
				System.out.println("女");
			}
		} // 河北省, 女
		
		/**
		 * 轉換字元串大小寫 - toUpperCase()  toLowerCase()
		 * 使用後原字元串大小寫不變
		 */
		String strSmall = "asdfg";
		String strSmall2 = "QWER";
		System.out.println(strSmall.toUpperCase()); // ASDFG
		System.out.println(strSmall); // asdfg
		System.out.println(strSmall2.toLowerCase()); // qwer
	}
}
           
String s1 = "aaa";
		s1 = s1 + "sss";
		String s2 = s1;
		System.out.println(s1); // aaasss
		System.out.println(s2); // aaasss
           

另一篇字元串替換的文章 : http://blog.csdn.net/qq_28261207/article/details/68924423