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

前端 未结 9 1286
轻奢々
轻奢々 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:33

    Solution without regex

    name.chars().mapToObj(i -> (char) i + " ").collect(Collectors.joining()).strip()
    

    Don't like regex because compile method slow

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

    This will space out all letters in each word and not between words

    "Joe Black".replaceAll("\\B", " ") -> "J o e B l a c k"
    

    This will put space for each character (including original spaces)

    "Joe Black".replaceAll("\\B|\\b", " ") -> " J o e  B l a c k "
    
    0 讨论(0)
  • 2020-12-03 11:36
    char[] stringArray = strOrig.toCharArray(); 
    StringBuilder sb = new StringBuilder();
    
    for(int index=0; index < stringArray.length; index++) {
       sb.append(stringArray[index]);
       sb.append(" ");
    }
    
    0 讨论(0)
提交回复
热议问题