您好,登錄后才能下訂單哦!
代碼如下:
public class TempTest { public static void main(String[] args) { //string去除空格 String str=" hello world "; System.out.println(str); String str1=str.trim();//去除首尾空格 System.out.println(str1); String str2=str.replace(" ","");//去掉所有空格,包括首尾,中間 System.out.println(str2); String str3=str.replaceAll(" +","");//去掉所有空格,包括首尾,中間 System.out.println(str3); String str4=str.replaceAll("\\s*",""); //可以替換大部分空白字符, 不限于空格 . 說(shuō)明:\s 可以匹配空格、制表符、換頁(yè)符等空白字符的其中任意一個(gè) System.out.println(str4); //string去除標(biāo)點(diǎn)符號(hào) //正則表達(dá)式去除標(biāo)點(diǎn) String stri="ss&*(,.~1如果@&(^-自己!!知道`什`么#是$苦%……Z,&那*()么一-=定——+告訴::;\"'/?.,><[]{}\\||別人什么是甜。"; System.out.println(stri); String stri1=stri.replaceAll("\\p{Punct}","");//不能完全清除標(biāo)點(diǎn) System.out.println(stri1); String stri2=stri.replaceAll("\\pP","");//完全清除標(biāo)點(diǎn) System.out.println(stri2); String stri3=stri.replaceAll("\\p{P}","");//同上,一樣的功能 System.out.println(stri3); String stri4=stri.replaceAll("[\\pP\\p{Punct}]","");//清除所有符號(hào),只留下字母 數(shù)字 漢字 共3類(lèi). System.out.println(stri4); } }
運(yùn)行結(jié)果:
hello world
hello world
helloworld
helloworld
helloworld
ss&*(,.~1如果@&(^-自己!!知道`什`么#是$苦%……Z,&那*()么一-=定——+告訴::;"'/?.,><[]{}\||別人什么是甜。
ss1如果自己知道什么是苦……Z,那么一定——告訴別人什么是甜。
ss~1如果^自己知道`什`么是$苦Z那么一=定+告訴><||別人什么是甜
ss~1如果^自己知道`什`么是$苦Z那么一=定+告訴><||別人什么是甜
ss1如果自己知道什么是苦Z那么一定告訴別人什么是甜
關(guān)于replace 和replaceAll:
replace(char oldChar,char newChar) replace(CharSequence target,CharSequence replacement) replaceAll(String regex,String replacement)
1)replace的參數(shù)是char和CharSequence,即可以支持字符的替換,也支持字符串的替換(CharSequence即字符串序列的意思,說(shuō)白了也就是字符串);
2)replaceAll的參數(shù)是regex,即基于規(guī)則表達(dá)式的替換,比如,可以通過(guò)replaceAll("\\d", "*")把一個(gè)字符串所有的數(shù)字字符都換成星號(hào);
相同點(diǎn)是都是全部替換,即把源字符串中的某一字符或字符串全部換成指定的字符或字符串,如果只想替換第一次出現(xiàn)的,可以使用 replaceFirst(),這個(gè)方法也是基于規(guī)則表達(dá)式的替換,但與replaceAll()不同的是,只替換第一次出現(xiàn)的字符串;
另外,如果replaceAll()和replaceFirst()所用的參數(shù)據(jù)不是基于規(guī)則表達(dá)式的,則與replace()替換字符串的效果是一樣的,即這兩者也支持字符串的操作;
還有一點(diǎn)注意:執(zhí)行了替換操作后,源字符串的內(nèi)容是沒(méi)有發(fā)生改變的.
總結(jié)
到此這篇關(guān)于java去除空格、標(biāo)點(diǎn)符號(hào)的文章就介紹到這了,更多相關(guān)java去除空格、標(biāo)點(diǎn)符號(hào)內(nèi)容請(qǐng)搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。