Java使用類-String

来源:https://www.cnblogs.com/xiaoqigui/archive/2022/06/16/16383071.html
-Advertisement-
Play Games

大佬的理解->《深入理解Java中的String》 1、String 1.1 String 實例化 String str1 = "xxx"; String string1 = "hello KH96"; System.out.println(string1); //hello KH96 String ...


大佬的理解->《深入理解Java中的String》

1、String

1.1 String 實例化

String str1 = "xxx";

String string1 = "hello KH96";
System.out.println(string1); //hello KH96

String str1 = new String("xxx");

String string2 = "hello KH96";
System.out.println(string2); //hello KH96

String底層實現 private final char value[];

​ String底層是由私有final的數組實現的,對外沒有提供修改的方法,字元串多次賦值,不是修改字元串的內容,而是改變字元串的引用地址

源碼

1.2 String常用方法

方法 說明
length() 字元串的長度
equals() 比較的是字元串的內容
equalsIgnoreCase(String str) 忽略大小比較
toUpperCase() 轉大寫
toLowerCase() 轉小寫
concat(String str) 返回拼接後的字元串

length()

字元串的長度:length()方法,返回的是字元串的長度,即字元串的長度(不是位元組數),區別去數組的length

String string1 = "hello KH96";
System.out.println(string1+"的長度:"+string1.length()); //hello KH96的長度:10

equals()

重寫了Object類的equals方法,比較的是字元串的內容,不是對象

String string2 = "KH96";
String string3 = "KH97";
System.out.println(string2.equals(string3)); //false

equalsIgnoreCase(String str)

忽略大小比較

String string7 = "kh96";
String string8 = "KH96";
System.out.println("不忽略大小寫比較:"+string7.equals(string8)); //false
System.out.println("忽略大小寫比:"+string7.equalsIgnoreCase(string8)); //true

toUpperCase() 轉大寫 toLowerCase() 轉小寫

String string9 = "abCD";
System.out.println(string9.toUpperCase()); //ABCD
System.out.println(string9.toLowerCase());//abcd

concat(String str) 返回拼接後的字元串

"+"號也可以進行字元串拼接

concat(String str)

拼接字元串都創建了新的對象,在迴圈中儘量不要拼接字元串,會造成棧溢出;

String strig10 = "abc";
System.out.println(strig10.concat("bcd").concat("def"));//abcbcddef

1.3 String 字元查找/提取相關方法

方法 說明
indexOf(String str) 返回str首次出現的下標
lastIndexOf(String str) 返回str最後一次出現的下標
substring(int index1) 截取下標index1,及以後的所有字元
substring(int index1,int index2) 截取下標index1到index2之間的字元串,包括index1,不包括index2
trim() 去除字元串的首尾空格
startsWith(String str) 是否以str開頭
endsWith(String str) 是否以str結尾
contains(String str) 是否包含str
split(String str) 根據指定分割字元,將字元串拆分成字元串數組返回
toCharArray() 將字元串轉為字元數組
replace(String str1,String str2) 用 str2 替換 str1
getBytes() 字元串轉換為位元組數組
getBytes("UTF-8") 字元串轉換為位元組數組,可指定編碼
new String(byte[] bytes) 將位元組數組轉換為字元串

indexOf(String str)

返回str首次出現的下標,沒有查到就返回-1

String string11 = "I am a good student in kh96";
System.out.println("good首次出現的位置:"+string11.indexOf("good")); //7

還可以通過ascii碼值查詢

String string11 = "I am a good student in kh96";
char char1 = 97;
System.out.println(char1); //a
System.out.println("參數支持int assic碼值:"+string11.indexOf(97)); //2

lastIndexOf(String str)

返回str最後一次出現的下標,沒有就返回-1

String string11 = "I am a good student in kh96";
System.out.println(string11);
System.out.println("t最後一次出現的下標:"+string11.lastIndexOf("t")); //18

substring(int index1)

截取下標index1,及以後的所有字元

index的範圍[0,string.length()]

String string12 = "abcdefghijklmn";
System.out.println(string12.substring(5)); //fghijklmn

substring(int index1,int index2)

截取下標index1到index2之間的字元串,包括index1,不包括index2

index的範圍[0,string.length()]

String string12 = "abcdefghijklmn";
System.out.println(string12.substring(5,8)); //fgh

小應用

String string14 = "KH90,KH91,KH92,KH93,KH94,KH95,";
System.out.println(string14.substring(0,string14.lastIndexOf(",")));//KH90,KH91,KH92,KH93,KH94,KH95

trim()

去除字元串的首尾空格

String string13 = "  KH  96  ";
System.out.println("原始長度"+string13.length()); //10
System.out.println("取出空格後長度"+string13.trim().length()); //6 "KH  96"

startsWith(String str) endsWith(String str)

startsWith(String str) 是否以str開頭

endsWith(String str) 是否以str結尾

String string15 = "KH96.mp3";
System.out.println("是否是KH開頭?"+ string15.startsWith("KH")); //true
System.out.println("是否是.mp3結尾?"+ string15.endsWith(".mp3")); //true

contains(String str)

判斷字元串是否包含str

String string16 = "aaa bbb cc ddd";
System.out.println("是否包含bbb:"+ string16.contains("bbb")); //true
System.out.println("是否包含eee:"+ string16.contains("eee")); //false

split(String str)

根據指定分割字元,將字元串拆分成字元串數組返回

String string17_1 = "13501020304;15801020304;18901020304";
String[] phoneNumbers1 = string17_1.split(";"); //一種字元分割
System.out.println("手機號數組內容:"+ Arrays.toString(phoneNumbers2));

String string17_2 = "13501020304;15801020304!18901020304";
String[] phoneNumbers2 = string17_2.split(";|!"); //多種字元分割 用 | 隔開
System.out.println("手機號數組內容:"+ Arrays.toString(phoneNumbers2));
//[13501020304, 15801020304, 18901020304]

toCharArray()

將字元串轉為字元數組

char[] chars1 = string18.toCharArray();
System.out.println(Arrays.toString(chars1)); //[K, H, 9, 8, 正, 在, 學, 習, 實, 用, 類]

replace(String str1,String str2)

用 str2 替換 str1

//獲取一個16位的隨機字元串
 String string19 = UUID.randomUUID().toString();
System.out.println(string19); //65c0844a-c437-4a65-89ca-84d4166325ff

//轉換字元串,將-轉換為*
System.out.println(string19.replace("-","*"));//65c0844a*c437*4a65*89ca*84d4166325ff
//去除字元串,將所有的-去除
System.out.println(string19.replace("-",""));//65c0844ac4374a6589ca84d4166325ff
//去16位隨機數
System.out.println(string19.replace("-","").substring(0,16));//65c0844ac4374a65

getBytes() getBytes("UTF-8")

字元串轉換為位元組數組

String string20 = "abcd";
//getBytes() 沒有指定編碼
byte[] bytes = string20.getBytes(); 
try {
    //getBytes("UTF-8") 指定編碼
    byte[] bytes2 = string20.getBytes("UTF-8");
    System.out.println(Arrays.toString(bytes2)); //[97, 98, 99, 100]
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
System.out.println(Arrays.toString(bytes)); //Arrays.toString(bytes)

new String(byte[] bytes)

將位元組數組轉換為字元串

 byte[] bytes3 ={100,101,102}; //ascii碼值
System.out.println(new String(bytes3)); //def
//配合上面getBytes進行轉碼
try {
    System.out.println(new String(bytes3,"utf-8")); //可以指定編碼 def
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

char[] chars3 = {'K','H','9','6'};
System.out.println(new String(chars3));//KH96

2、StringBuffer

可變字元串類:StringBuffer
不同於String類:可以實現動態拼接字元串,而不會創建新的對象;
即:是一個可變字元串的對象,改變的是字元串對象中的內容;
不可以直接賦值,必須通過new創建對象;

2.1 StringBuffer實例化

new StringBuffer()

預設初始容量 16

StringBuffer sbf1 = new StringBuffer();
System.out.println("預設初始容量:"+sbf1.capacity());//16

底層實現

//StringBuffer()
public StringBuffer() {
        super(16); //初始容量16
    }

//AbstractStringBuilder(int capacity)
AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}

new StringBuffer(int capacity)

指定初始容量

StringBuffer sbf2 = new StringBuffer(32);
System.out.println("只定始容量:"+sbf2.capacity()); //32

底層實現

public StringBuffer(int capacity) {
	super(capacity); //指定初始容量
}

StringBuffer(String str)

指定初始字元串,容量為字元串長度+16

StringBuffer sbf3 = new StringBuffer("Kh96");
System.out.println("指定初始字元串初始容量:"+sbf3.capacity()); //20

底層實現

public StringBuffer(String str) {
    super(str.length() + 16); //容量為字元串長度+16
    append(str);
}

2.2 StringBuffer常用方法

append(String str)

拼接字元串

StringBuffer sbf4 = new StringBuffer("userId=");
sbf4.append("U0001")
            .append(",userName=")
            .append("張三,age=")
            .append("18"); //userId=U0001,userName=張三,age=18

擴容機制

底層擴容,當拼接一個新的字元串,字元串數組長度不夠,會進行動態擴容,
每次擴容都是前一個數組長度的2倍+2
最大擴容長度不能超過Integer的最大值 - 8;

void expandCapacity(int minimumCapacity) {
    int newCapacity = value.length * 2 + 2; //每次擴容都是前一個數組長度的2倍+2
    if (newCapacity - minimumCapacity < 0)
        newCapacity = minimumCapacity;
    if (newCapacity < 0) {
        if (minimumCapacity < 0) // overflow
            throw new OutOfMemoryError();
        newCapacity = Integer.MAX_VALUE;
    }
    value = Arrays.copyOf(value, newCapacity);
}

toString()

獲取動態字元串內容

StringBuffer sbf4 = new StringBuffer("userId=");
sbf4.append("U0001")
            .append(",userName=")
            .append("張三,age=")
            .append("18");
String userInfo = sbf4.toString();
 System.out.println(userInfo); //userId=U0001,userName=張三,age=18

3、StringBuilder

用法和StringBuffer沒有區別,唯一的區別就是StringBuffer是線程安全的,StringBuilder是非線程安全的


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、前言 單例模式屬於創建型模式,保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。 單例模式確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例,這個類稱為單例類,它提供全局訪問的方法。 2、介紹 2.1、主要解決 防止一個系統全局使用的類頻繁地創建與銷毀、解決多線程併發訪問的問題 ...
  • 1 前言 函數調用很好理解,即使剛學沒多久的朋友也知道函數調用是怎麼實現的,即調用一個已經封裝好的函數,實現某個特定的功能。 把一個或者多個功能通過函數的方式封裝起來,對外只提供一個簡單的函數介面,然後在其他地方調用即可 2 函數調用方式 函數調用難道還能怎麼調用?不就封裝好直接調用嗎??? 函數調 ...
  • 目錄 一.簡介 二.效果演示 三.源碼下載 四.猜你喜歡 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 轉場 零基礎 O ...
  • 一、Pycharm軟體簡介 產品簡介 PyCharm是一種Python IDE(Integrated Development Environment,集成開發環境),帶有一整套可以幫助用戶在使用Python語言開發時提高其效率的工具,比如調試、語法高亮、項目管理、代碼跳轉、智能提示、自動完成、單元測 ...
  • 一. 打包參數 1. * 的作用:在函數定義中,收集所有的位置參數到一個新的元組,並將這個元組賦值給變數args >>> def f(*args): print(args) >>> f() () >>> f(1) (1,) >>> f(1, 2, 3, 4) (1, 2, 3, 4) >>> 2. ...
  • 1、Date 1.1 Date實例化 Date date1 = new Date(); System.out.println(date1); //Thu Jun 16 19:18:56 CST 2022 1.2 獲取日期毫秒數 getTime() System.out.println(date1.g ...
  • 大家好!我們是阿裡云云效智能代碼天團!旨在用人工智慧解放各位開發者的生產力!或許你們關註過我們的話會知道,我們有一個超酷的產品它叫Alibaba Cloud AI Coding Assistant,小名兒叫Cosy。說起這代碼補全和代碼搜索那可是樣樣精通٩(˃̶͈̀௰˂̶͈́)و 我們不僅把文檔搬進 ...
  • 今天來點特別的~ 不僅把好看的視頻全部pa下來,咱們還要實現自動評論、點贊、關註三連~ 寶,你也可以順手給我個三連嗎?給你個摸摸大~ 抓包分析流程 我寫成了文檔,都在這個PDF裡面了,但是好像不能上傳,所以點一下大家自行下載吧! 點我獲取,提取密碼 qwer 開始代碼 獲取視頻的代碼 import ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...