![](/img/trans.png)
[英]how can I check if user insert more than one word , space or special char?
[英]How do I insert a word if the string has more than one space in Java?
我有以下代碼,
String s = " Hello I'm a multi spaced String"
在字符串s中,有多個(不確定的)空格; 但是,我需要將其打印為%temp%Hello I'm a%temp%multi spaced String
我怎樣才能做到這一點?
像這樣使用regex \\s{2,}
和replaceAll()
方法:
s.replaceAll("\\s{2,}","%temp%");
產量
%temp%Hello I'm a%temp%multi spaced String
碼
public class HelloWorld
{
public static void main(String[] args)
{
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s{2,}","%temp%");
System.out.println(s);
}
}
您可以使用正則表達式,如\\s\\s+
,它匹配一個空格,后跟一個或多個額外的空格。 就像是,
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s\\s+", "%temp%");
System.out.println(s);
產出(按要求)
%temp%Hello I'm a%temp%multi spaced String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.