Java_String

1:Scanner的使用(瞭解)

(1)在JDK5以後出現的用於鍵盤錄入數據的類。

(2)構造方法:

A:講解了System.in這個東西。

它其實是標準的輸入流,對應於鍵盤錄入

B:構造方法

InputStream is = System.in;

Scanner(InputStream is)

C:常用的格式

Scanner sc = new Scanner(System.in);

(3)基本方法格式:

A:hasNextXxx() 判斷是否是某種類型的

B:nextXxx()返回某種類型的元素

(4)要掌握的兩個方法

A:public int nextInt()

B:public String nextLine()

(5)需要注意的小問題

A:同一個Scanner對象,先獲取數值,再獲取字符串會出現一個小問題。

                Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
                String s=sc.nextLine();		
		System.out.println(n+"\t"+s);
        //輸入5回車後直接輸出結果 5
        //換行符號已經佔據字符串輸入的位置

B:解決方案:

a:重新定義一個Scanner對象

b:把所有的數據都用字符串獲取,然後再進行相應的轉換

2:String類的概述和使用(掌握)

(1)多個字符組成的一串數據。

其實它可以和字符數組進行相互轉換。

(2)構造方法:

A:public String() //空構造

直接輸出對象名,輸出的是對象名的原始toString()方法。

                String s=new String();
		System.out.println("s:"+s);
		System.out.println("s.length:"+s.length());

輸出:

s:

s.length:0 

        B:public String(byte[] bytes) 字節數組轉換成字符串

byte[] bys={97,98,99,45,105};
		String s=new String(bys);
		System.out.println("s:"+s);
		System.out.println("s.length:"+s.length());

輸出:

s:abc-i

s.length:5

將字節通過ASC碼轉換成字符後輸出


        C:public String(byte[] bytes,int offset,int length)  字節數組的一部分轉換成字符串

                byte[] bys={97,98,99,45,105};
		String s=new String(bys,1,3);//從1號元素開始截取長度3的內容
		System.out.println("s:"+s);
		System.out.println("s.length:"+s.length());

輸出:

s:bc-

s.length:3


D:public String(char[] value)   字符數組轉換成字符串

                char[] chs={'a','b','c','d','f','牛'};
		String s=new String(chs);
		System.out.println("s:"+s);
		System.out.println("s.length:"+s.length());

輸出:

s:abcdf牛

s.length:6


E:public String(char[] value,int offset,int count)  字符數組的一部分轉換成字符串

                char[] chs={'a','b','c','d','f','牛'};
		String s=new String(chs,2,4);
		System.out.println("s:"+s);
		System.out.println("s.length:"+s.length());

輸出:

s:cdf牛

s.length:4

F:public String(String original) 字符串常量轉換爲字符串

String s = new String( "ABCDE" );

相當於

String s = "ABCDE";


下面的這一個雖然不是構造方法,但是結果也是一個字符串對象

G:String s = "hello";


(3)字符串的特點

A:字符串一旦被賦值,就不能改變。

注意:這裏指的是字符串的內容不能改變,而不是引用不能改變。

                “Hello”不可變,對應的內存地址可以變

B:字面值作爲字符串對象和通過構造方法創建對象的不同

String s = new String("hello");和String s = "hello"的區別?

                                s+= "World";

直接賦值:String s = "hello"

    創建一個對象(方法區)或不需創建(方法區已有對象)。    

    先到方法區字符常量池裏面找,如果有就直接返回,沒有就創建並返回“hello”的內存地址。

    先創建“Hello”地址,之後創建“World”地址,最後重新開一個地址儲存“HelloWorld”

創建對象:String s = new String("hello");

     創建兩個(堆內存和方法區)對象或一個對象(方法區內已有對象)。

    new String()先在堆內存中開空間,然後到方法區找,類似直接賦值,地址返回堆內存,堆內存地址再返回棧內存。所以和直接賦值相比,接收到的“Hello”對應的內存地址不同

(4)字符串的面試題(看程序寫結果)

==     比較引用類型比較的是地址值是否相同

equals  比較引用類型也是比較地址值是否相同,而String類重寫了equals()方法,比較的是內容是否相同

#################################################################################

A:==和equals()


String s1 = new String("hello");

String s2 = new String("hello");

System.out.println(s1 == s2);// false 兩個對象都在堆內存,地址不同

System.out.println(s1.equals(s2));// true 內容相同


String s3 = new String("hello");

String s4 = "hello";

System.out.println(s3 == s4);// false一個是堆內存地址,一個是方法區內存地址

System.out.println(s3.equals(s4));// true內容相同


String s5 = "hello";

String s6 = "hello";

System.out.println(s5 == s6);// true s5以創建方法區內存,s6直接使用,所以內存地址相同

System.out.println(s5.equals(s6));// true 內容相同


B:字符串的拼接

String s1 = "hello";

String s2 = "world";

String s3 = "helloworld";

System.out.println(s3 == s1 + s2);// false s3已有方法區內存地址,s1+s2 會重新開方法區內存,所以內存地址不同

System.out.println(s3.equals((s1 + s2)));// true內容相同


System.out.println(s3 == "hello" + "world");// true  先將兩個常量“hello”和“world”相加後發現有s3,所以等同於s3的方法區內存地址

字符串變量相加: 先開空間,再拼接;

字符串常量相加:先拼接,然後在方法區常量池找,如果有就直接使用,沒有的話再創建

System.out.println(s3.equals("hello" + "world"));// true內容相同


(5)字符串的功能(自己補齊方法中文意思)

A:判斷功能

boolean equals(Object obj)

區分大小寫比較字符串的內容是否相同


boolean equalsIgnoreCase(String str)

忽略大小寫比較字符串內容是否相同


boolean contains(String str)

判斷大字符串中是否包含小字符串


boolean startsWith(String str)

判斷字符串是否已某個制定字符串開始


boolean endsWith(String str)

判斷字符串是否已某個制定字符串結束


boolean isEmpty()

判斷字符串是否爲空

內容爲空:String s = “”; 空

對象爲空:String s = null; 無對象,無法調方法


B:獲取功能

int length()    

獲取字符串長度


char charAt(int index)    

獲取指定位置的字符


int indexOf(int ch)    

返回指定字符第一次出現的位置

爲什麼是int而不是char ‘a’和‘97’都可以表示‘a’,如果限定爲char則需要由大到小強轉


int indexOf(String str)    

返回指定字符串在此字符串中第一次出現的位置


int indexOf(int ch,int fromIndex)  

返回指定字符在此字符串從指定位置之後第一次出現的位置


int indexOf(String str,int fromIndex)

返回指定字符串在此字符串從指定位置之後第一次出現的位置


String substring(int start)    

從指定位置開始截取子字符串,默認到末尾


String substring(int start,int end)  

從指定範圍截取字符串



C:轉換功能

byte[] getBytes()

字符串轉換爲字節數組

String s="admin";

byte[] b=s.getBytes();//輸出的是每個字符的字節碼


char[] toCharArray()

字符串轉換爲字符數組

String s="admin";

char[] c=s.toCharArray();


static String valueOf(char[] chs)

字符數組轉換成字符串

        String s="admin"

        char[] chs=s.toCharArray();

String ss = String.valueOf(chs);

System.out.println(ss)


static String valueOf(int i)

int轉換爲字符串

valueOf()方法可以將任意類型的數據轉換爲字符串

int i = 100;

String sss = String.valueOf(i);

System.out.println(sss);


String toLowerCase()

字符串轉換爲小寫

        String s="admin";

System.out.println("toLowerCase:" + s.toLowerCase());

System.out.println("s:" + s);


String toUpperCase()

字符串轉換爲大寫


String concat(String str)

字符串拼接


D:其他功能

a:替換功能 

String replace(char old,char new)

public class Test {
	public static void main(String[] args) {
		String s="helloWorld";
		String s2=s.replace('l', 'k');
		System.out.println(s);
		System.out.println(s2);
	}
}

輸出:

helloWorld

hekkoWorkd


String replace(String old,String new)

新字符即使更長也可直接拼接進去

public class Test {
	public static void main(String[] args) {
		String s="helloWorld";
		String s2=s.replace("ell", "WWW");
		System.out.println(s);
		System.out.println(s2);
	}
}

輸出:

helloWorld

hWWWoWorld


b:去空格功能

String trim() 

去除字符串兩邊的空格


c:按字典比較功能

int compareTo(String str)    區分大小寫

public class Test {
	public static void main(String[] args) {
		String s="456";
		String s2="456";
		String s3="123";
		String s4="789";
		System.out.println(s.compareTo(s2));
		System.out.println(s.compareTo(s3));
		System.out.println(s.compareTo(s4));
	}
}

輸出:

0

3

-3

字符串長度不同時,

從前往後依次對比字符是否相同,相同爲0,不同時得出的結果是不同的字符字節碼的差數

  private final char value[];

  

    字符串會自動轉換爲一個字符數組。

  

  public int compareTo(String anotherString) {

  //this -- s1 -- "hello"

  //anotherString -- s2 -- "hel"

//獲取第一個字符數組的長度

        int len1 = value.length; //this.value.length--s1.toCharArray().length--5

        //獲取第二個字符數組的長度

int len2 = anotherString.value.length;//s2.value.length -- s2.toCharArray().length--3

        

//獲取兩個字符數組長度中較小的值

int lim = Math.min(len1, len2); //Math.min(5,3); -- lim=3;

        

char v1[] = value; //s1.toCharArray()

        char v2[] = anotherString.value;

        

        //char v1[] = {'h','e','l','l','o'};

        //char v2[] = {'h','e','l'};

//以較短字符數組長度爲界限,依次對比,找出不同時返回字節碼的差

        int k = 0;

        while (k < lim) {

            char c1 = v1[k]; //c1='h','e','l'

            char c2 = v2[k]; //c2='h','e','l'

            if (c1 != c2) {

                return c1 - c2;

            }

//前面都相同時,比較完較短字符數組的全部元素即跳出

            k++;

        }

//對比完較短數組後返回兩個數組長度的差

        return len1 - len2; //5-3=2;

   }

   

   String s1 = "hello";

   String s2 = "hel";

   System.out.println(s1.compareTo(s2)); // 2


int compareToIgnoreCase(String str) 不區分大小寫


(6)字符串的案例

A:模擬用戶登錄

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		String name="admin";
		int pass=123456;
		Scanner sc=new Scanner(System.in);
		System.out.println("請輸入用戶名:");
		String uname=sc.nextLine();
		System.out.println("請輸入密碼:");
		int upass=sc.nextInt();
		for(int i=0;i<3;i++){
			if(name.equals(uname)&&pass==upass){
				System.out.println("恭喜,登錄成功!");
				break;
			}else if(name.equals(uname)){
				System.out.println("登錄失敗,密碼輸入錯誤,你還有"+(3-i)+"次機會。");
				System.out.println("請輸入用戶名:");
				Scanner sc2=new Scanner(System.in);
				uname=sc2.nextLine();
				System.out.println("請輸入密碼:");				
				upass=sc.nextInt();
			}else if(upass==pass){
				System.out.println("登錄失敗,用戶名輸入錯誤,你還有"+(3-i)+"次機會。");
				System.out.println("請輸入用戶名:");
				Scanner sc2=new Scanner(System.in);
				uname=sc2.nextLine();
				System.out.println("請輸入密碼:");				
				upass=sc.nextInt();
				
			}else{
				System.out.println("登錄失敗,你還有"+(3-i)+"次機會,請重新輸入:");
				System.out.println("請輸入用戶名:");
				Scanner sc2=new Scanner(System.in);
				uname=sc2.nextLine();
				System.out.println("請輸入密碼:");				
				upass=sc.nextInt();
			}
			if(i==2){
				System.out.println("登錄失敗,次數已使用完畢");
			}
		}
		sc.close();		
	}
}

有BUG 關於close()待解決


另一種方法:

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		String name = "admin";
		String pass = "123456";
		for (int i = 0; i < 3; i++) {
			Scanner sc = new Scanner(System.in);
			System.out.println("請輸入用戶名:");
			String uname = sc.nextLine();
			System.out.println("請輸入密碼:");
			String upass = sc.nextLine();
			if (uname.equals(name) && upass.equals(pass)) {
				System.out.println("登錄成功!");
				sc.close();
				break;
			} else {
				if ((2 - i) == 0) {
					System.out.println("登錄失敗,請聯繫管理員!");
					sc.close();
				} else {
					System.out.println("登錄失敗,還有" + (2 - i) + "次機會");
				}
			}
		}
	}
}



B:字符串遍歷

String s="Hello World!";
for(int i=0;i<s.length();i++){
    System.out.println(s.charAt(i));
}

輸出:

H

e

l

l

o

 

W

o

r

l

d

!


C:統計字符串中大寫,小寫及數字字符的個數

public class Test {
	public static void main(String[] args) {
		String s = "Hello123World!";
		int bigCount = 0;
		int smallCount = 0;
		int numberCount = 0;
		//遍歷字符串,得到每一個字符
		//通過 length()和charAt()結合取出每個字符
		// char ch = s.charAt(i);
		for(int i=0;i<s.length();i++){
			char ch=s.charAt(i);
			if(ch>='0'&&ch<='9'){
				numberCount++;
			}else if(ch>='a'&&ch<='z'){
				smallCount++;
			}else if(ch>='A'&&ch<='Z'){
				bigCount++;
			}			
		}
		System.out.println("numberCount:"+numberCount);
		System.out.println("smallCount:"+smallCount);
		System.out.println("bigCount:"+bigCount);
	}
}

輸出:

numberCount:3

smallCount:8

bigCount:2


改進:將字符串換成接收用戶輸入的字符串。

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		System.out.println("請輸入一個字符串:");
		String s=sc.nextLine();
		Show(s);
		sc.close();
	}
	
	//創建一個獲取指定字符串各項值數量的方法
	public static void Show(String s){
		int bigCount = 0;
		int smallCount = 0;
		int numberCount = 0;
		//遍歷字符串,得到每一個字符
		//通過 length()和charAt()結合取出每個字符
		// char ch = s.charAt(i);
		for(int i=0;i<s.length();i++){
			char ch=s.charAt(i);
			if(ch>='0'&&ch<='9'){
				numberCount++;
			}else if(ch>='a'&&ch<='z'){
				smallCount++;
			}else if(ch>='A'&&ch<='Z'){
				bigCount++;
			}			
		}
		System.out.println("numberCount:"+numberCount);
		System.out.println("smallCount:"+smallCount);
		System.out.println("bigCount:"+bigCount);
	}
}

輸出:

請輸入一個字符串:

ADSDF12345sgsg

numberCount:5

smallCount:4

bigCount:5


D:把字符串的首字母轉成大寫,其他小寫

public class Test {
	public static void main(String[] args) {
		//將首字符轉換爲大寫,其餘小寫
		String s="helloWorld";
		//獲取第一個字符
		String s1=s.substring(0,1);
		//獲取1之後的字符串
		String s2=s.substring(1);
		//首字符大寫
		String s3=s1.toUpperCase();
		//其餘字符轉小寫
		String s4=s2.toLowerCase();
		//拼接字符串
		String s5=s3.concat(s4);
		System.out.println(s5);
	}
}

輸出:

Helloworld


另一種方法:通過鏈式編程不斷調方法解決

String s="helloWorld";
String ss=s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());
System.out.println(ss);

輸出:

Helloworld



E:把int數組拼接成一個指定格式的字符串

public class Test {
	public static void main(String[] args) {
		//新建一個空字符串
		String s = "";
		int[] num = { 1, 2, 3, 4, 5, 6 };
		//字符串添加一個【符號
		s += "[";
		for (int i = 0; i < num.length; i++) {
			//判斷元素是否爲數組最後一個
			if (i == num.length - 1) {
				//如果是最後一個就直接拼接元素和】符號
				s += num[i];
				s += "]";
			} else {
				//如果不是就拼接元素和逗號,空格
				s += num[i];
				s += ", ";
			}
		}
		System.out.println(s);
	}
}

輸出:

[1, 2, 3, 4, 5, 6]


F:字符串反轉

import java.util.Scanner;

/*
 * 字符串反轉
 * 舉例:鍵盤錄入”abc”		
 * 輸出結果:”cba”
 * 
 * 分析:
 * 		A:鍵盤錄入一個字符串
 * 		B:定義一個新字符串
 * 		C:倒着遍歷字符串,得到每一個字符
 * 			a:length()和charAt()結合
 * 			b:把字符串轉成字符數組
 * 		D:用新字符串把每一個字符拼接起來
 * 		E:輸出新串
 */
public class StringTest3 {
	public static void main(String[] args) {
		// 鍵盤錄入一個字符串
		Scanner sc = new Scanner(System.in);
		System.out.println("請輸入一個字符串:");
		String line = sc.nextLine();

		/*
		// 定義一個新字符串
		String result = "";

		// 把字符串轉成字符數組
		char[] chs = line.toCharArray();

		// 倒着遍歷字符串,得到每一個字符
		for (int x = chs.length - 1; x >= 0; x--) {
			// 用新字符串把每一個字符拼接起來
			result += chs[x];
		}

		// 輸出新串
		System.out.println("反轉後的結果是:" + result);
		*/

		// 改進爲功能實現
		String s = myReverse(line);
		System.out.println("實現功能後的結果是:" + s);
	}

	/*
	 * 兩個明確: 返回值類型:String 參數列表:String
	 */
	public static String myReverse(String s) {
		// 定義一個新字符串
		String result = "";

		// 把字符串轉成字符數組
		char[] chs = s.toCharArray();

		// 倒着遍歷字符串,得到每一個字符
		for (int x = chs.length - 1; x >= 0; x--) {
			// 用新字符串把每一個字符拼接起來
			result += chs[x];
		}
		return result;
	}
}


另一種:

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("請輸入一個字符串:");
		String s = sc.nextLine();
		Change(s);
		sc.close();
	}

	public static void Change(String s) {
		// 字符串轉換爲字符數組
		char[] ch = s.toCharArray();
		char temp = ch[0];
		// for循環翻轉字符數組
		for (int i = 0; i < ch.length / 2; i++) {
			temp = ch[i];
			ch[i] = ch[ch.length - i - 1];
			ch[ch.length - i - 1] = temp;
		}
		// 字符數組轉化爲字符串
		String ss = String.valueOf(ch);
		System.out.println(ss);
	}
}


G:統計大串中小串出現的次數

public class Test {
	public static void main(String[] args) {
		String s = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
		String str = "java";
		int count = Search(s, str);
		System.out.println("子字符串" + str + "共出現" + count + "次");
		String s1="123456789123456789";
		String s2="123";
		System.out.println(s1.contains("9"));
		System.out.println(Search(s1,s2));
	}

	public static int Search(String s1, String s2) {
		//s1爲原始字符串,s2爲待檢索的子字符串
		int count = 0;
		// contains()方法判斷是否包含字串
		while (s1.contains(s2)) {
			// substring()方法截取搜索後剩餘部分的字符串
			// indexOf()方法獲取子串第一次出現的位置
			// length()方法得到字串的長度
			// 第一次出現的座標加上字串長度即爲剩餘字符串的起始座標
			s1 = s1.substring((s1.indexOf(s2) + s2.length()));
			// 當包含字串時,此時加一
			count++;
		}
		return count;
	}
}

輸出:

子字符串java共出現5次

true

2



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章