常見物件String和其方法+JAVA學習筆記-DAY12
阿新 • • 發佈:2018-11-04
12.01: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():獲取一個int型別的值
B:public String nextLine():獲取一個String型別的值
(5)需要注意的小問題
A:同一個Scanner物件,先獲取數值,再獲取字串會出現一個小問題。
B:解決方案:
a:重新定義一個Scanner物件
b:把所有的資料都用字串獲取,然後再進行相應的轉換
12.02:String類的概述和使用(掌握)
(1)多個字元組成的一串資料。
其實它可以和字元陣列進行相互轉換。
(2)構造方法:
- A:public String()
- B:public String(byte[] bytes)
- C:public String(byte[] bytes,int offset,int length)
- D:public String(char[] value)
- E:public String(char[] value,int offset,int count)
- F:public String(String original)
下面的這一個雖然不是構造方法,但是結果也是一個字串物件 G:String s = “hello”;
public class StringDemo { public static void main(String[] args) { // public String():空構造 String s1 = new String(); System.out.println("s1:" + s1); System.out.println("s1.length():" + s1.length()); System.out.println("--------------------------"); // public String(byte[] bytes):把位元組陣列轉成字串 byte[] bys = { 97, 98, 99, 100, 101 }; String s2 = new String(bys); System.out.println("s2:" + s2); System.out.println("s2.length():" + s2.length()); System.out.println("--------------------------"); // public String(byte[] bytes,int index,int length):把位元組陣列的一部分轉成字串 // 我想得到字串"bcd" String s3 = new String(bys, 1, 3); System.out.println("s3:" + s3); System.out.println("s3.length():" + s3.length()); System.out.println("--------------------------"); // public String(char[] value):把字元陣列轉成字串 char[] chs = { 'a', 'b', 'c', 'd', 'e', '愛', '林', '親' }; String s4 = new String(chs); System.out.println("s4:" + s4); System.out.println("s4.length():" + s4.length()); System.out.println("--------------------------"); // public String(char[] value,int index,int count):把字元陣列的一部分轉成字串 String s5 = new String(chs, 2, 4); System.out.println("s5:" + s5); System.out.println("s5.length():" + s5.length()); System.out.println("--------------------------"); //public String(String original):把字串常量值轉成字串 String s6 = new String("abcde"); System.out.println("s6:" + s6); System.out.println("s6.length():" + s6.length()); System.out.println("--------------------------"); //字串字面值"abc"也可以看成是一個字串物件。 String s7 = "abcde"; System.out.println("s7:"+s7); System.out.println("s7.length():"+s7.length()); } }
(3)字串的特點
- A:字串一旦被賦值,就不能改變。
注意:這裡指的是字串的內容不能改變,而不是引用不能改變。 - B:字面值作為字串物件和通過構造方法建立物件的不同
- String s = new String(“hello”);和String s = “hello”的區別?
- 有。前者會建立2個物件,後者建立1個物件。
- String s = new String(“hello”);和String s = “hello”的區別?
(4)字串的面試題(看程式寫結果)
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 System.out.println(s5.equals(s6));// true
B:字串的拼接
- 字串如果是變數相加,先開空間,在拼接。
字串如果是常量相加,是先加,然後在常量池找,如果有就直接返回,否則,就建立。
String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; System.out.println(s3 == s1 + s2);// false System.out.println(s3.equals((s1 + s2)));// true System.out.println(s3 == "hello" + "world");// false 這個我們錯了,應該是true 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():判斷字串是否為空。
* ""和null的區別
* ""是字串常量,同時也是一個String類的物件,可以呼叫String類的方法
* null是空常量,不能呼叫任何方法,否則會出現空指標異常,null可以給任意的引用資料型別賦值
public class StringDemo {
public static void main(String[] args) {
// 建立字串物件
String s1 = "helloworld";
String s2 = "helloworld";
String s3 = "HelloWorld";
// boolean equals(Object obj):比較字串的內容是否相同,區分大小寫
System.out.println("equals:" + s1.equals(s2));
System.out.println("equals:" + s1.equals(s3));
System.out.println("-----------------------");
// boolean equalsIgnoreCase(String str):比較字串的內容是否相同,忽略大小寫
System.out.println("equals:" + s1.equalsIgnoreCase(s2));
System.out.println("equals:" + s1.equalsIgnoreCase(s3));
System.out.println("-----------------------");
// boolean contains(String str):判斷大字串中是否包含小字串
//System.out.println("contains:" + s1.contains("hello"));
//System.out.println("contains:" + s1.contains("hw"));
System.out.println("-----------------------");
// boolean startsWith(String str):判斷字串是否以某個指定的字串開頭
System.out.println("startsWith:" + s1.startsWith("h"));
System.out.println("startsWith:" + s1.startsWith("hello"));
System.out.println("startsWith:" + s1.startsWith("world"));
System.out.println("-----------------------");
// 練習:boolean endsWith(String str):判斷字串是否以某個指定的字串結尾這個自己玩
// boolean isEmpty():判斷字串是否為空。
System.out.println("isEmpty:" + s1.isEmpty());
String s4 = "";
String s5 = null;
System.out.println("isEmpty:" + s4.isEmpty());
// NullPointerException
// s5物件都不存在,所以不能呼叫方法,空指標異常
//System.out.println("isEmpty:" + s5.isEmpty());
}
}
B:獲取功能
int length():獲取字串長度
char charAt(int index):獲取指定索引位置的字元
int indexOf(int ch):返回指定字元在此字串中第一次出現的索引
int indexOf(String str):返回指定字串在此字串中第一次出現的索引
int indexOf(int ch,int fromIndex):返回指定字元在此字串中從指定位置後第一次出現處的索引。
int indexOf(String str,int fromIndex):返回指定字串在此字串中從指定位置後第一次出現處的索引。
String substring(int start):返回指定字串在此字串中從指定位置後第一次出現處的索引。包含start這個索引。
String substring(int start,int end):從指定位置開始到指定位置結束擷取字串。包括start索引但是不包end索引
案例
public class StringDemo { public static void main(String[] args) { // 定義一個字串物件 String s = "helloworld"; // int length():獲取字串的長度。 System.out.println("s.length:" + s.length()); System.out.println("----------------------"); // char charAt(int index):獲取指定索引位置的字元 System.out.println("charAt:" + s.charAt(7)); System.out.println("----------------------"); // int indexOf(int ch):返回指定字元在此字串中第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf('l')); System.out.println("----------------------"); // int indexOf(String str):返回指定字串在此字串中第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf("owo")); System.out.println("----------------------"); // int indexOf(int ch,int fromIndex):返回指定字元在此字串中從指定位置後第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf('l', 4)); System.out.println("indexOf:" + s.indexOf('k', 4)); // -1 System.out.println("indexOf:" + s.indexOf('l', 40)); // -1 System.out.println("----------------------"); // 自己練習:int indexOf(String str,int // fromIndex):返回指定字串在此字串中從指定位置後第一次出現處的索引。 // String substring(int start):從指定位置開始擷取字串,預設到末尾。包含start這個索引 System.out.println("substring:" + s.substring(5)); System.out.println("substring:" + s.substring(0)); System.out.println("----------------------"); // String substring(int start,int // end):從指定位置開始到指定位置結束擷取字串。包括start索引但是不包end索引 System.out.println("substring:" + s.substring(3, 8)); System.out.println("substring:" + s.substring(0, s.length())); } }
C:轉換功能
byte[] getBytes():通過GBK碼錶,把字串轉換為位元組陣列。(可設定:選中專案,右鍵-properties-Rescource-Text file encoding)
編碼:把我們看的懂的轉換為計算機看的懂的,gbk碼錶的一箇中文代表兩個位元組,中文的第一個位元組肯定是負數
char[] toCharArray():把字串轉換為字元陣列。
static String valueOf(char[] chs):把字元陣列轉成字串。
static String valueOf(int i):把int型別的資料轉成字串。
注意:String類的valueOf方法可以把任意型別的資料轉成字串。
String toLowerCase():把字串轉成小寫。
String toUpperCase():把字串轉成大寫。
String concat(String str):把字串拼接。
D:其他功能
a:替換功能
String replace(char old,char new)
String replace(String old,String new)
b:去空格功能
String trim()
c:按字典比較功能
int compareTo(String str) 按照碼錶值來比較
int compareToIgnoreCase(String str)
(6)字串的案例
A:模擬使用者登入
package com.laviniatu.String_03;
import java.util.Scanner;
public class Login {
/*
* 模擬登入,給三次機會,並提示還有幾次。
* 使用者名稱和密碼都是admin
* 分析:
* A:定義使用者名稱和密碼。已存在的。
* B:鍵盤錄入使用者名稱和密碼。
* C:比較使用者名稱和密碼。
* 如果都相同,則登入成功
* 如果有一個不同,則登入失敗
* D:給三次機會,用迴圈改進,最好用for迴圈。
*/
public static void main(String[] args) {
String admin = "admin";
String pass = "admin";
Scanner cin = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
System.out.println("請輸入使用者名稱");
String InAdmin = cin.nextLine();
System.out.println("請輸入密碼");
String InPass = cin.nextLine();
if (admin.equals(InAdmin)&&pass.equals(InPass)) {
System.out.println("登入成功");
break;
}else {
if (i==3) {
System.out.println("第"+i+"次登入失敗,賬號已鎖定");
}else {
System.out.println("第"+i+"次登入失敗,還剩"+(3-i)+"次機會");
}
}
}
}
}
B:字串遍歷
public class GetEveryCharFromString {
/*需求:遍歷獲取字串中的每一個字元
*
* 分析:
* A:如何能夠拿到每一個字元呢?
* char charAt(int index)
* B:我怎麼知道字元到底有多少個呢?
* int length()*/
public static void main(String[] args) {
String string = "hello我們world";
for (int i = 0; i < string.length(); i++) {
System.out.println("第"+i+"個字元是:"+string.charAt(i));
}
}
}
C:統計字串中大寫,小寫及數字字元的個數
public class CountNumChar {
/*
* 需求:統計一個字串中大寫字母字元,小寫字母字元,數字字元出現的次數。(不考慮其他字元)
* 舉例:
* "Hello123World"
* 結果:
* 大寫字元:2個
* 小寫字元:8個
* 數字字元:3個
*
* 分析:
* 前提:字串要存在
* A:定義三個統計變數
* bigCount=0
* smallCount=0
* numberCount=0
* B:遍歷字串,得到每一個字元。
* length()和charAt()結合
* C:判斷該字元到底是屬於那種型別的
* 大:bigCount++
* 小:smallCount++
* 數字:numberCount++
*
* 這道題目的難點就是如何判斷某個字元是大的,還是小的,還是數字的。
* ASCII碼錶:
* 0 48
* A 65
* a 97
* 雖然,我們按照數字的這種比較是可以的,但是想多了,有比這還簡單的
* char ch = s.charAt(x);
*
* if(ch>='0' && ch<='9') numberCount++
* if(ch>='a' && ch<='z') smallCount++
* if(ch>='A' && ch<='Z') bigCount++
* D:輸出結果。
*
* 練習:把給定字串的方式,改進為鍵盤錄入字串的方式。
*/
public static void main(String[] args) {
String string = "Hello22World70";
int NumCount = 0;
int BigCount = 0;
int SmallCount = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i)>='0'&&string.charAt(i)<='9') {
NumCount++;
}else if (string.charAt(i)>='a'&&string.charAt(i)<='z') {
SmallCount++;
}else if (string.charAt(i)>='A'&&string.charAt(i)<='Z') {
BigCount++;
}
}
System.err.println("數字個數:"+NumCount);
System.err.println("大寫字母個數:"+BigCount);
System.err.println("小寫字母個數:"+SmallCount);
}
}
D:把字串的首字母轉成大寫,其他小寫
public class ConverString {
/*
* 需求:把一個字串的首字母轉成大寫,其餘為小寫。(只考慮英文大小寫字母字元)
* 舉例:
* helloWORLD
* 結果:
* Helloworld
*
* 分析:
* A:先獲取第一個字元
* B:獲取除了第一個字元以外的字元
* C:把A轉成大寫
* D:把B轉成小寫
* E:C拼接D
*/
public static void main(String[] args) {
String string = "helloWORLD";
String start = String.valueOf(string.charAt(0));
String res = string.substring(1);
String aString = start.toUpperCase();
String bString = res.toLowerCase();
String cString = aString.concat(bString);
System.out.println(cString);
//優化後
String dString = String.valueOf(string.charAt(0)).toUpperCase().concat(string.substring(1).toLowerCase());
System.out.println(dString);
}
}
E:把int陣列拼接成一個指定格式的字串
public class ArryToString {
/**
* 需求:把陣列中的資料按照指定格式拼接成一個字串
* 舉例: *int[] arr = {1,2,3};
* *輸出結果 "[1, 2, 3]"
*
*/
public static void main(String[] args) {
int [] arr = {1,5,6,9,12};
String string = "[";
for (int i = 0; i <arr.length; i++) {
if (i==arr.length-1) {
string = string + arr[i]+"]";
}else {
string = string + arr[i]+",";
}
}
System.out.println(string);
}
}
F:字串反轉
public class ReverString {
/* * 字串反轉
* 舉例:鍵盤錄入”abc”
* 輸出結果:”cba”*/
public static void main(String[] args) {
String string = "abcdefgh";
char[] ArrayString = string.toCharArray();
for (int i = 0; i < ArrayString.length/2; i++) {
char temp = ArrayString[i];
ArrayString[i] = ArrayString[ArrayString.length-1-i];
ArrayString[ArrayString.length-1-i] = temp;
}
string = String.valueOf(ArrayString);
System.out.println(string);
}
}
G:統計大串中小串出現的次數
public class CountStrFromString {
/*
* 統計大串中小串出現的次數
* 舉例:
* 在字串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"
* 結果:
* java出現了5次
*
* 分析:
* 前提:是已經知道了大串和小串。
*
* A:定義一個統計變數,初始化值是0
* B:先在大串中查詢一次小串第一次出現的位置
* a:索引是-1,說明不存在了,就返回統計變數
* b:索引不是-1,說明存在,統計變數++
* C:把剛才的索引+小串的長度作為開始位置擷取上一次的大串,返回一個新的字串,並把該字串的值重新賦值給大串
* D:回到B
*/
public static void main(String[] args) {
String string = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
String str = "java";
menthod(string, str);
method1(string, str);
}
private static void method1(String string, String str) {
int index = 0;
int count = 0;
while ((index = string.indexOf(str))!= -1) {
count++;
string = string.substring(index+str.length());
}
System.out.println(count);
}
private static void menthod(String string, String str) {
int count = 0;//計數器
int index =0;//定義索引
while (index<string.length()){
index = string.indexOf(str,index+str.length());
if (index == -1) {
//System.out.println("結束");
break;
}else {
count++;
//System.out.println(index);
}
}
System.out.println(count);
}
}