在字符間添加空格
回答
您可以使用正則表達式'..'
每兩個字符相匹配,並與"$0 "
更換,以增加空間:
s = s.replaceAll("..", "$0 ");
您可能還需要修整的結果爲最終刪除多餘的空間。
看到它在線工作:ideone。
另外,您可以添加式斷言,以避免在字符串的結尾添加的空間:
s = s.replaceAll("..(?!$)", "$0 ");
謝謝,它的工作 –
我寫了這一個通用的解決方案......
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
然後調用像這樣......
String result = InsertSpaces.insertCharacterForEveryNDistance(2, "javastring", ' ');
System.out.println(result);
//Where n = no of character after you want space
int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
str.insert(idx, " ");
idx = idx - n;
}
return str.toString();
說明,該代碼會從右側添加空間到左:
str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
str.insert(idx, " "); //this will insert space at 6th position
idx = idx - n; // then decrement 6-2=4 and run loop again
}
最終輸出將是
AB CD EF GH
你可以添加一些詞來解釋這是如何工作的? – Kmeixner
此代碼將從右到左添加空格, str =「ABCDEFGH」 int idx =總長度-2; // 8-2 = 6 while(8> 0)str.insert(idx,「」 ); //這將在第6個位置插入空格 idx = idx - n; //然後遞減6-2 = 4並再次運行循環 } 最終輸出將爲AB CD EF GH 希望這篇文章有助於 –
- 1. 在字符間自動添加空格
- 2. 拆分字符串並在字符串之間添加空格
- 3. 在字母數字字符串中間添加空格
- 4. 在數字之間添加空格?
- 5. 在字母和特殊字符之間添加空格
- 6. 字符之間添加一個可選空格的字符串
- 7. 字符串中的字符之間添加一個空格
- 8. 在字符串右側添加空格
- 9. 在Typoscript中添加空格字符
- 10. 在字符串中添加空格
- 11. 添加數字/數字和字母/之間的空格字符
- 12. 向空間中添加一個空格的字符串
- 13. PHP腳本在每個字符之間添加一個空格
- 14. 在空格之外的每個字符之間添加一個#
- 15. 在用戶輸入的字符串之間添加空格
- 16. SAS如何在字符串之間添加空格?
- 17. Python:如何在字符串之間添加空格
- 18. 正則表達式 - 在替換字符之間添加空格
- 19. 在兩個字符串之間添加變量空格
- 20. Python:Unicode源文件在字符之間添加空格(實際上是空字節)
- 21. 如何在字符串後添加空格並刪除空格?
- 22. 如何在字符串中添加多個空格(空格?)?
- 23. 在某些字符之前在字符串中添加空格
- 24. 如何在字符串中的每個字符之間添加空格?
- 25. 在excel中添加3個字符後用VBA添加空格
- 26. 我想在數字和字母數字字符之間添加空格
- 27. 將空格添加到字符串
- 28. 添加空格/拆分字符對
- 29. 添加尾隨空格爲字符串
- 30. PHP:將空格添加到字符串
可能重複:HTTP://stackoverflow.com/questions/4469984/how-to-insert-space-after-character-of-an-an-string-in-java – Zakaria
使用for或while指令循環字符串變量,並在兩個字符後打印空格! – alibenmessaoud