如何在Java中现有字符串的每个字符之后插入空格?

2022-09-02 02:11:38

我需要在字符串的每个字符后插入一个空格。

String name = "Joe";

应变为:"J o e"


答案 1

更短将使用正则表达式:

System.out.println("Joe".replaceAll(".(?!$)", "$0 "));

答案 2

对于 Android 和 Kotlin 用户,如果你想在每个 X 字符后添加空格,请使用 this

val stringWithSpaceAfterEvery4thChar = stringWith12Chars?.replace("....".toRegex(), "$0 ")

在这里,我在方法中添加了4个点,以在整个字符串中的每4个字符之后添加空格。如果您希望每 2 个字符后留出空格,则在方法中仅添加 2 个点

我的变量:

stringWith12Chars = "123456789012"

输出将是,

stringWithSpaceAfterEvery4thChar = "1234 5678 9012"