2013-12-13 19 views
3
   String test="This is a simple text" 

是否可以通過查找此空格來檢測空格並寫入下一行?我的意思是有一個這樣的控制檯輸出:如何檢測字符串中的空格?

     This is a simple text 
         ++++ ++ + ++++++ ++++ 
+1

對於每個字符,如果不是空格,寫一個'+',否則寫一個空格。 –

+1

看看['Character.isWhitespace'](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isWhitespace(char))。 – rgettman

回答

1
public class StringPlus { 

    public static void main(String[] args) { 
     String test="This is a simple text"; 
     for(char c: test.toCharArray()){ 
      System.out.print((c == ' ') ? " ":"+"); 
     } 
    } 
} 
1

您可以使用:

String orig = "This is a simple text"; 
String newString = orig.replaceAll("[^\\s]", "+"); 

它使用正則表達式來替換它不是白色的空間有加號的所有字符。

+0

實際上,所有不是空格的字符(製表符,空格,換行符)。在這種情況下,它可能會起作用,但您可以使用否定空間。 –

1

遍歷String,並在每次迭代中連接到新的String。如果原始String中的字符不等於空格,則將+連接到新字符串,否則將空格連接到新的String

+1

那就是答案! – Diversity

1

我認爲最簡單的方法是循環並手動構建它。其他方法可能涉及使用正則表達式(例如,如果您知道一組輸入字符)與string.replace一起使用。

這裏有一個循環可能是什麼樣子:

StringBuilder sb = new StringBuilder(inputString.length); 
for (char c : inputString) { 
    if (Character.isWhiteSpace(c)) { 
    sb.append("*"); 
    } else { 
    sb.append(" "); 
} 
return sb.toString(); 
0

使用Character.isWhitespace(ch),例如

public static void main(final String[] args) { 
    String test = "This is a simple text"; 
    System.out.println(test); 
    for (char ch : test.toCharArray()) { 
     System.out.print(Character.isWhitespace(ch) ? " " : "+"); 
    } 
}