How to insert Space after every Character of an existing String in Java?

前端 未结 9 1285
轻奢々
轻奢々 2020-12-03 11:01

I need to insert a space after every character of a string.

i.e. String name = \"Joe\";

should become: \"J o e\"

相关标签:
9条回答
  • 2020-12-03 11:21

    Shorter would be using a regex:

    System.out.println("Joe".replaceAll(".(?!$)", "$0 "));
    
    0 讨论(0)
  • 2020-12-03 11:21

    For Android & Kotlin users, if you want to add space after every X characters then use this

    val stringWithSpaceAfterEvery4Chars = stringWith16Chars?.replace("....".toRegex(), "$0 ")
    

    Here I added 4 dots in method to add space after every 4th character in my whole string. If you want space after every 2 characters then add only 2 dots in the method.

    My variables:

    stringWith16Chars = "123456789012"
    

    and the output would be,

    stringWithSpaceAfterEvery4Chars = "1234 5678 9012"
    
    0 讨论(0)
  • 2020-12-03 11:26

    Something like:

    String joe = "Joe";
    StringBuilder sb = new StringBuilder();
    
    for (char c: joe.toCharArray()) {
       sb.append(c).append(" ");
    }
    
    System.out.println(sb.toString().trim());
    
    0 讨论(0)
  • 2020-12-03 11:30

    Using kotlin

    val textToBeDevided = "123456789" 
    textToBeDevided
       .subSequence(1, textToBeDevided.length) 
       .chunked(3) // group every 3 chars
       .joinToString(" ") // merge them applying space
    
    0 讨论(0)
  • 2020-12-03 11:32

    You can convert Joe to char[] by using String's toCharArray() then traverse char[] to grab the char into another char[] and as you add the char to the second char[], you add a space character '" "'. Set a if-else within the loop to detect the last character so that you wouldn't add a space character by accident behind the last character. Use a String to valueOf() the resulting char[] to turn it into a String object.

    0 讨论(0)
  • 2020-12-03 11:33

    Removing the final space:

    String joe = "Joe"; 
    StringBuilder sb = new StringBuilder(); 
    String sep = "";
    for (char c: joe.toCharArray()) { 
        sb.append(sep).append(c);
        sep = " ";
    } 
    
    System.out.println(sb.toString()); 
    
    0 讨论(0)
提交回复
热议问题