Java基礎入門之字符串的轉換、替換、刪除和判斷
大家好,我是Java進階者,今天小編帶大家一起來學習Java技術基礎!
一、字符串的轉換
1.在開發過程中,有時需要對字符串的轉換操作,例如字符串的字母大小寫轉換把”abc”轉換成”ABC”,基本數據類型轉換成字符串、字符數組轉換成字符串,字符串轉成數組的形式等。
2.字符串轉換的方法:
String toUpperCase():把字符串轉換成大寫。
String toLowerCase():把字符串轉換成小寫。
char[] toCharArray():把字符串轉換成一個字符數組。
String(byte[],offset,count):將字節數組中的一部分轉換成字符串。
String valueOf(int i):返回int參數的字符串表示形式 。
String(byte[]):字節數組轉換成字符串。
String(char[]):字符數組轉換成字符串。
String(char[],offset,count):字符數組中的一部分轉換成字符串。
3.字符串轉換操作的例子:
- public class p44 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //字符數組轉換成字符串
- char[] c1={'A','B','C','D'};
- String str1=String.valueOf(c1);
- System.out.println("This is : "+str1);
- //字符串轉換成字符數組
- String str2="JAVA";
- char[] c2=str2.toCharArray();
- for (int i=0;i<str2.length();i++){
- System.out.println("第"+(i+1)+"個"+c2[i]);
- }
- //字符串轉換成大寫
- String str3="hello,world!";
- System.out.println("字符串轉換成大寫:"+str3.toUpperCase());
- //字符串轉換成小寫
- String str4="JAVA EE!";
- System.out.println("字符串轉換成小寫:"+str4.toLowerCase());
- }
- }
運行的結果是:
二、字符串的替換和刪除空格
1.在開發過程中,當用戶在輸入的時,有時候會把數據輸入錯誤和空格。我們可以使用String類提供方法中的replace()和trim(),把字符串的替換和刪除空格。
2.字符串的替換和刪除空格方法
String trim( ):去掉字符串開頭和結尾的空格。
String replace(char oldChar,char newChar):把這個字符串中的oldChar字符轉換為newChar字符來創建一個新的字符串。
3.字符串的替換和刪除空格例子
- public class p45 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str1="this is a apple";
- //字符串的替換
- System.out.println("把le替換成lication的結果:"+str1.replace("le", "lication"));
- //字符串的刪除空格
- String str2=" hello w o r l d !";
- System.out.println("刪除字符串兩端空格結果:"+str2.trim());
- //刪除字符串中所有空格
- System.out.println("刪除字符串中所有空格結果:"+str2.replace(" ",""));
- }
- }
運行的結果是:
三、字符串的判斷
1.在開發過程中,有時需要對一些字符串進行判斷的操作,例如判斷字符串是否相等、判斷字符是不是以指定的字符串開始、結尾等。
2.字符串判斷常用的方法
boolean startsWith(String prefix) 判斷字符串是否以指定字符串開頭。
boolean endsWith(String sufix) 判斷是否以指定的字符串結尾。
boolean equals(Object anObject) 判斷字符串是否相等。
boolean isEmpty()判斷字符串的長度是否為空,如果字符串長度為0,返回true。
boolean equalsIgnoreCase()判斷字符串是否相等,并忽略大小寫 。
boolean contains(str)判斷字符串中是否包含某一個子串。
3.字符串判斷的例子:
- public class p46 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str1="Application";
- String str2="apple";
- String str3="appliCation";
- System.out.println("判斷str1是否以字符串App開頭:"+str1.startsWith("App"));
- System.out.println("判斷str2是否以字符串ple結尾:"+str2.endsWith("ple"));
- System.out.println("判斷str1和str2的字符串是否相等,結果是"+str1.equals(str2));
- System.out.println("判斷str2字符串是否為空,結果是"+str2.isEmpty());
- System.out.println("判斷str1字符串是否包含cat,結果是"+str1.contains("cat"));
- //判斷字符串是否相等,并忽略大小寫
- System.out.println("判斷str1和str3的字符串是否相等,并忽略大小寫,結果是"+str1.equalsIgnoreCase(str3));
- }
- }
運行的結果是:
四、總結
本文主要介紹了字符串的轉換、替換和刪除空格、判斷。
字符串轉換介紹了的方法,通過例子幫助理解這個字符串轉換的方法,例如字符串大小寫的轉換等。
字符串的替換和刪除空格的方法是replace()和trim()。
字符串的判斷介紹了一些常用的方法,例如判斷字符串是否相等、判斷字符是不是以指定的字符串開始、結尾等。