30

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?

E.g. given "JAYARAM", I need "J A Y A R A M" as the result.

1

14 Answers 14

66

Unless you want to loop through the string and do it "manually" you could solve it like this:

yourString.replace("", " ").trim()

This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.

ideone.com demonstration


An alternative solution using regular expressions:

yourString.replaceAll(".(?=.)", "$0 ")

Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".

ideone.com demonstration

Documentation of...

Sign up to request clarification or add additional context in comments.

8 Comments

+1 correct answer. At last... someone who can actually use java properly (instead of creating loads of junk wheel-reinvention)
@Bohemian - It may be a one-liner, but not everyone will understand it.
Added documentation links (and an alternative non-regexp solution) for those people ;-)
@aioobe Could you please help me out in learning how regular expression actually works, I have looked into sun's sites, but dont understand much. I mean simply asking how did you form the ".(?=.)" ? and also what does it mean by "$0 " ?? Could please suggest me any site/materiel which explains in simpler manner ? It ll be a great help.
This answer whilst its the best of the lot here, does not consider the level of understanding of the OP. For loops == baby steps ;)
|
12
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
   if (i > 0) {
      result.append(" ");
    }

   result.append(input.charAt(i));
}

System.out.println(result.toString());

Comments

4

Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.

Something like this :

StringBuilder result = new StringBuilder();

for(int i = 0 ; i < str.length(); i++)
{
   result = result.append(str.charAt(i));
   if(i == str.length()-1)
      break;
   result = result.append(' ');
}

return (result.toString());

3 Comments

@Bohemian : I already read and also voted up. I am new to regex, so dint quite understand. I have already started learning :)
@Swagatika: Don't blindly follow his advice. Regexes are an interesting tool, but involve a performance hit and of course are harder to read to many programmers. Use what is most appropriate. Also: You may not have recognized, but there's a high dose of arrogance in Bohemians post, and arrogance should always make you skeptical.
@phresnel: Thanks for your advice. I am not following anyone. Just that its a new topic for me, which I really want to learn to make better judgments of its appropriate use.
2

Blow up your String into array of chars, loop over the char array and create a new string by succeeding a char by a space.

4 Comments

It IS the most effective solution. Just not the one taking the less characters to implement.
What makes it "wrong" is that it's the "wrong approach". ie "here's one idea of how to do it, but it's not a good one so don't every do this in your code"
@Bohemian: It depends on what you want to achieve. If this is in the core of millions-of-lines CSV parser that needs to do crappy char-to-wchar conversion, regexes couldn't be wronger, so maybe please stop trying to enlighten us from your godlike experience.
While this answer is not the most effective, it suits the complexity level of the question. Don't expect someone that doesn't the answer to this question to understand regex expressions....baby steps people!!
2

Create a StringBuilder with the string and use one of its insert overloaded method:

StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
    sb.insert(i, ' ');
System.out.println(sb.toString());

The above prints:

J A Y A R A M

Comments

1

This would work for inserting any character any particular position in your String.

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();
}

Then call it like this

String result = InsertSpaces.insertCharacterForEveryNDistance(1, "5434567845678965", ' ');
        System.out.println(result);

Comments

1

I am creating a java method for this purpose with dynamic character

public String insertSpace(String myString,int indexno,char myChar){
    myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
    System.out.println(myString);
    return myString;
}

1 Comment

Please add some explanation as to why your code works, as opposed to just providing a solution. That way others will be able to understand the answer. As a side note, having a mutating method that prints out is bad form, and it doesn't answer the question because the questionner wanted a space in between each letter, not just as a method to insert a space at a specific point.
0

This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:

String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
    result.append(input.charAt(0));
    for (int i = 1; i < input.length(); i++) {
        result.append(" ");
        result.append(input.charAt(i));
    }
}

Comments

0
public static void main(String[] args) {
    String name = "Harendra";
    System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0  "));
    System.out.println(String.valueOf(name).replaceAll(".", "$0  "));
}

This gives output as following use any of the above:

H a r e n d r a

H a r e n d r a

Comments

0

One can use streams with java 8:

String input = "JAYARAM";
input.toString().chars()
    .mapToObj(c -> (char) c + " ")
    .collect(Collectors.joining())
    .trim();
// result: J A Y A R A M

Comments

0

A simple way can be to split the string on each character and join the parts using space as the delimiter.

Demo:

public class Main {
    public static void main(String[] args) {
        String s = "JAYARAM";
        s = String.join(" ", s.split(""));
        System.out.println(s);
    }
}

Output:

J A Y A R A M

ONLINE DEMO

Comments

-1
  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

2 Comments

concatenating using + in a loop is really a bad advice.
Aioobe's answer might be the best....but for a question like this, MY answer outlines how the beginner level programmer(assumed from the complexity of the question) should approach the problem.
-1

If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.

Or creating a char array and converting it back to the string would yield the same result.

Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.

Comments

-2

I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break) and \u00A0 (for spacing) or alternatively $#032

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.