1、字符串的判斷方法:
以上方法例子:
public class StringDemo4 {
public static void main(String[] args) {
//創建常理的字符串
String str = "helloworld";
//判斷字符串是否以ld結尾
System.out.println(str.endsWith("world"));
//判斷兩個字符串是否相等,equals比較的是值
System.out.println(str.equals("helloworld"));
//建議使用,不會發生空指針的異常
System.out.println("helloworld".equals(str));
//不區分大小寫的比較,驗證碼的校驗
System.out.println("HELLOWORLD".equalsIgnoreCase(str));
//判斷是否包含某段連續的字符串
System.out.println(str.contains("hello"));
//判斷是否以某段字符串開頭
System.out.println(str.startsWith("hel"));
//判斷字符串是否是空串
System.out.println(str.isEmpty());
System.out.println("".isEmpty());
//獲得字符串的長度,空格是字符,空串長度是0
System.out.println(" ".length());
}
}
2、字符串的獲取功能:
例子如下:
public static void main(String[] args) {
String str = "helloworlld";
//從指定索引處查找第一次出現的字符串的索引,包含開始索引的本身
int index = str.indexOf("ll", 3);
System.out.println(index);
//獲得子字符串,包括索引本身後面的所有字符
String str1 = str.substring(8);
System.out.println(str1);
//根據開始和結束的索引來獲得子字符串, 包括開始索引,不包括結束的索引
String str2 = str.substring(2, 5);
System.out.println(str2);
//獲得字符串對應的字節數組
byte [] bs = str.getBytes();
for(int i = 0 ; i < bs.length; i++){
System.out.print(bs[i]+"\t");
}
System.out.println();
//把字符串轉換成字符數組
char [] cs = str.toCharArray();
for(int i = 0 ; i < cs.length; i++){
System.out.print(cs[i]+"\t");
}
System.out.println();
//把布爾類型轉換成字符串類型
String strboolean = String.valueOf(true);
System.out.println(strboolean);
char[] c = {'d','g','h'};
//String cArray = String.valueOf(new char[]{'1','g','g','h'});
String cArray = String.valueOf(c);
System.out.println(cArray);
//把字符串轉換成大寫
String str6 = "txjava";
System.out.println(str6.toUpperCase());
String str7 = "TXJAVA";
System.out.println(str7.toLowerCase());
//拼接字符串
System.out.println(str6.concat(str7));
System.out.println(str6+str7);
}
}
3、實例:計算一個字符串中大寫字母,小寫字母和數字的數量。
public class StringDemo7 {
/**
* 計算一個字符串中大寫字母和小寫字母還有數字的數量
* 分析:大寫字母,小寫字母,數字如果篩選有兩種方法
比較值或者比較ASCII碼
*/
public static void main(String[] args) {
//創建Scanner對象
Scanner sc = new Scanner(System.in);
//獲得我們輸入字符串
String str = sc.nextLine();
parseStr(str);
}
public static void parseStr(String str){
int upperCount = 0;
int lowerCount = 0;
int num = 0;
//遍歷字符串"HelloWorld"
//獲得字符串的長度
/**
int length = str.length();
for(int i = 0; i < length; i++){
//獲得每一個字符的ascii
int c = str.charAt(i);
if(c >= 65 && c <= 90){
upperCount++;
}else if(c >= 97 && c <= 122){
lowerCount++;
}else if(c >= 48 && c <= 57){
num++;
}
}
*/
int length = str.length();
for(int i = 0; i < length; i++){
//獲得每一個字符
char c = str.charAt(i);
if(c >= 'A' && c <= 'Z'){
upperCount++;
}else if(c >= 'a' && c <= 'z'){
lowerCount++;
}else if(c >= '0' && c <= '9'){
num++;
}
}
System.out.println("大寫字母個數:"+upperCount);
System.out.println("小寫字母個數:"+lowerCount);
System.out.println("數字:"+num);
}
4、小結:
①判斷連個字符串是否相等,用equals,equals比較的是值,比較最好用:“helloworld”.equals(Str)來比較,這樣使用是防止不會出現空指針異常。
②在獲得字符串的長度時,空格是字符,空串長度是0。
③掌握API1.6中String類的用法。