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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Jey
  • 383
  • 2
  • 4
  • 6
  • 1
    This is homework, right? If so, then tag it with the homework tag. What have you tried. Have you read the String javadoc? http://download.oracle.com/javase/6/docs/api/java/lang/String.html – JB Nizet Aug 25 '11 at 11:08

14 Answers14

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...

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 4
    +1 correct answer. At last... someone who can actually use java properly (instead of creating loads of junk wheel-reinvention) – Bohemian Aug 25 '11 at 11:10
  • 4
    @Bohemian - It may be a one-liner, but not everyone will understand it. – Petar Minchev Aug 25 '11 at 11:11
  • 2
    Added documentation links (and an alternative non-regexp solution) for those people ;-) – aioobe Aug 25 '11 at 11:18
  • @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. – Swagatika Aug 25 '11 at 11:25
  • @Swagatik, I provided two links in my answer for *precisely* those two parts of the answer! – aioobe Aug 25 '11 at 11:26
  • 1
    This answer whilst its the best of the lot here, does not consider the level of understanding of the OP. For loops == baby steps ;) – gotomanners Aug 25 '11 at 11:58
  • I got this using the following String str = "name+= last_name"; str = str.replaceAll("(.)", "$0 "); Not sure why we have to use ".(?=.)" – Raj Dec 18 '13 at 21:04
  • @Raj, because you get a trailing white-space otherwise. (Which was not in line with what the OP posted in his example.) – aioobe Dec 18 '13 at 22:18
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());
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
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());
Swagatika
  • 3,376
  • 6
  • 30
  • 39
  • 2
    @Bohemian : I already read and also voted up. I am new to regex, so dint quite understand. I have already started learning :) – Swagatika Aug 25 '11 at 11:47
  • 3
    @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. – Sebastian Mach Aug 25 '11 at 11:59
  • 2
    @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. – Swagatika Aug 25 '11 at 12:04
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
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
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.

Trefex
  • 2,290
  • 16
  • 18
  • 5
    It IS the most effective solution. Just not the one taking the less characters to implement. – JB Nizet Aug 25 '11 at 11:23
  • 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 Aug 25 '11 at 11:25
  • 6
    @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. – Sebastian Mach Aug 25 '11 at 11:33
  • 1
    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!! – gotomanners Aug 25 '11 at 11:56
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);
Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78
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;
}
Balram Dixit
  • 408
  • 5
  • 7
  • 1
    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. – AlBlue Jul 12 '16 at 08:36
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

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

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
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
renatodamas
  • 16,555
  • 8
  • 30
  • 51
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));
    }
}
fbjon
  • 1
  • 1
-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!!
gotomanners
  • 7,808
  • 1
  • 24
  • 39
  • concatenating using + in a loop is really a bad advice. – JB Nizet Aug 25 '11 at 11:11
  • 1
    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. – gotomanners Aug 25 '11 at 11:53
-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.

user892871
  • 1,025
  • 3
  • 13
  • 28
-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