簡體   English   中英

如果字符串在Java中有多個空格,我該如何插入一個單詞?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM