在Java中,刪除刪除字符串末尾的字符作出操作可以通過(guò)以下幾種方法實(shí)現:
(圖片來(lái)源網(wǎng)絡(luò ),侵刪)1、串末使用substring()方法
2、尾操使用(?⊿?)replaceFirst()方法
3、刪除使用ヾ(′ω`)?charAt()方法
方法一:使用substring()方法
subs??tring()方法可以用于截取字符串的串末一部分,要刪除字符串末尾的尾操字符,可以先獲取字符串的刪除長(cháng)度,然后從長(cháng)度減1的字符作出位置開(kāi)始截取,直到字符串末尾。串末
示例代碼:
public class Main { public static void main(String[] args) { String str = "Hello??,尾操 world!"; int length = str.length(); str = str.substring(0, length 1); System.out.println(str);(′_ゝ`) // 輸出:Hello, world }}方法二:使用replaceFirst()方法
replaceFir??st()方法可以用于替換字符串中的第一個(gè)匹配項,要刪除字符串末尾的刪除字符,可以使用正則表達式$來(lái)匹配字符串末尾的字符作(zuo)出字符,并將其替換為(wei)空字符串。串末
示例代碼:
pu( ?ヮ?)blic class Main { public static void main(??String[] args) { String str = &q(′_ゝ`)uot;Hello, world!"; str = str.replaceFirst("\$", ""); System.out.println(str); // 輸出:Hello, world }}方法三:使用charAt()方法
charAt()(′ω`)方法可??以用于獲取字符串中指(zhi)定位(′?`)置的字符,要刪除字符串末尾的字符,可以??從字符串末尾開(kāi)始向前遍歷,直到遇到第一個(gè)非末尾的字符為止。
示例代碼:
public class Main { public sta(′?`)tic void main(Str(′?`)ing[] args) { String str = "Hello, world!"; int length = str.length(); for (int i = length 1; i >= 0; i) { if?? (str.charAt(i) != '!') { strヽ(′▽?zhuān)?ノ = str.substring(0, i + 1); break; } } System.out.println(str); // 輸出:Hell(′▽?zhuān)?o, world?? }}以上三種方法都可以實(shí)(?⊿?)現刪除字符串末尾的操作,具體選擇哪種方法取決于實(shí)(???)際需求和編程??習??慣,在實(shí)際開(kāi)發(fā)中,可以根據??具體情況選擇合適的方法。