0

I'm trying to print out a string with spaces on either side of each char in the string

so if I have

String s = "abcde"

it would create something like this

 a   b   c   d   e 

with a space before the first char and three between each char.

I just haven't been able to find a way to do this with my knowledge.

Anthony
  • 51
  • 6
  • 1
    Possibly consider `String.charAt()` and a loop over the length of the input String. Note that more advanced approaches would be required if the input could have, e.g., emojis. – KevinO Mar 25 '21 at 20:07

6 Answers6

3

Update

Updated requirement:

I failed to realize that I need something that add one place in front of the first term and then 3 spaces between each term. _0___0___0___0___0_ for example.

For the updated requirement, you can use yet another cool thing, String#join.

public class Main {
    public static void main(String[] args) {
        String s = "abcde";

        String result = "_" + String.join("___", s.split("")) + "_";

        System.out.println(result);
    }
}

Output:

_a___b___c___d___e_

Original answer

There can be so many ways to do it. I find it easier to do it using Regex:

public class Main {
    public static void main(String[] args) {
        String s = "abcde";
        String result = s.replaceAll(".", " $0 ");
        System.out.println(result);
    }
}

Output:

 a  b  c  d  e 

The Regex, . matches a single character and $0 replaces this match with space + match + space.

Another cool way is by using Stream API.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String s = "abcde";
        
        String result = Arrays.stream(s.split(""))
                                .map(str -> " " + str + " ")
                                .collect(Collectors.joining());
        
        System.out.println(result);
    }
}

Output:

 a  b  c  d  e 
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Ive never used Stream looks interesting. However, I failed to realize that I need something that add one place in front of the first term and then 3 spaces between each term. `_0___0___0___0___0_` for example. – Anthony Mar 25 '21 at 21:21
  • @Anthony - I've posted an update for this requirement. – Arvind Kumar Avinash Mar 25 '21 at 21:29
2

A super simple example, that doesn't handle a multitude of potential input scenarios.

    public static void main(String[] args)
    {
        String s = "abcde";
        
        
        for (int i = 0; i < s.length(); ++i) {
            System.out.print("_" + s.charAt(i));
        }
        System.out.println("_");
    }

NOTE: used an underscore rather than a space in order to allow visual check of the output.

Sample output:

_a_b_c_d_e_

Rather than direct output, one could use a StringBuilder and .append to a builder instead, for example.

Using StringBuilder:

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ++i) {
            sb.append('_').append(s.charAt(i));
        }
        sb.append('_');        
        
        System.out.println(sb.toString());

Based on a comment where the desired output is slightly different (two internal spaces, one leading and trailing space), this suggests an alternative approach:

   public static String addSpace(String inp) {
        StringBuilder sB = new StringBuilder();
        
        String string = inp.trim();
        
        String div = "___";  // spaces, or whatever
        
        
        sB.append('_');  // add leading space
        for(int index = 0; index < string.length(); ++index) {
            sB.append(string.charAt(index))
                .append(div);  // two spaces  
         }
        sB.setLength(sB.length() - (div.length() - 1) );
        
        return (sB.toString());
    }

NOTE: again using an underscore to allow for easier debugging.

Output when div is set to 3 underscores (or spaces):

_0___0___0___1___0___1___1___0_
KevinO
  • 4,303
  • 4
  • 27
  • 36
  • I'll try it with a StringBuilder because I need to input it back into a variable for use later, I've just never used it before. Thanks! – Anthony Mar 25 '21 at 20:16
  • That seems to be adding two spaces in front but I'm needed a space to the left and right. – Anthony Mar 25 '21 at 20:25
  • @Anthony, how so? It adds one space before every letter, and then one to the end of the String. The sample output does not indicate two spaces. What are you seeing that makes you believe you are seeing two leading spaces? – KevinO Mar 25 '21 at 20:27
  • When i wrote that into my code that is what it did. – Anthony Mar 25 '21 at 20:40
  • `"ab"` → `"_?_?_a_b_?_?_"` –  Mar 25 '21 at 20:45
  • `public String addSpace(String string) { StringBuilder sB = new StringBuilder(); for(int index = 0; index < string.length(); ++index) { sB.append("").append(string.charAt(index)); } sB.append(""); return (sB.toString()); } ` – Anthony Mar 25 '21 at 20:46
  • @saka1029 -- yes, emojis are problematic as I noted in a comment and in the leading comments. It *might* be the case they need to be handled, in which case I'd definitely use regex. But the OP did not so indicate. – KevinO Mar 25 '21 at 20:48
  • @Anthony, does your input String have leading or trailing spaces? Could it? If at all possible, I'd `trim()` the String. – KevinO Mar 25 '21 at 20:55
  • My string is "00010110" I am wanting `"_0___0___0___1___0___1___1___0_"`. When I use the string builder I get "____0____0____0____1____0_____1_____1_____0____". I cant get the – Anthony Mar 25 '21 at 20:59
  • @Anthony, I am really missing something. I took the exact code you posted, changed the `""` to `"_"` to allow for debugging, and go the following: `*_0_0_0_1_0_1_1_0_*` when calling as `System.out.println("*" + addSpace(s) + "*");`. Substituting a space for the "_", there is one space at the beginning and one at the end. The `*` are merely added in the print output to show nothing else is present. So I'm very confused as to what you are seeing. I even took what you entered for "wanting" and what you got, pasted into an editor, and there are no differences -- one space beginning and end. – KevinO Mar 25 '21 at 21:06
  • @Anthony, your latest wanting with the underscores is not what you said earlier. That has two spaces between each internal value, and one space at the beginning and the end. This output is not what you indicated. However, based upon this updated desire, I can make suggested adjustment. – KevinO Mar 25 '21 at 21:10
  • @KevinO Yes I am sorry. I thought I needed two spaces but I need three. But only one in the beginning and end like `_0___0___0___1___0___1___1___0_` – Anthony Mar 25 '21 at 21:15
  • @Anthony, I made an update to the answer. You can modify the `div` variable as needed for the internal division -- so 3 spaces if needed. – KevinO Mar 25 '21 at 21:20
  • @KevinO thank you that works! is the set length trimming it? What does that do? – Anthony Mar 25 '21 at 21:27
  • @Anthony, yes it is trimming the end StringBuilder. There are other ways to do so, of course. Glad it is working. – KevinO Mar 25 '21 at 21:28
  • @KevinO Cool! Thank you for the help and thank you for explaining that. – Anthony Mar 25 '21 at 21:37
1

You can define an empty string : result = “”;

Then go through the string you want to print with foreach loop With the function toCharArray()

(char character : str.toCharArray())

And inside this loop do ->

result += “ “ + character;

1
String result = s.chars().mapToObj(
                       Character::toString
                   ).collect(Collectors.joining(" "));

Similar to the loop versions, but uses a Stream.

matt
  • 10,892
  • 3
  • 22
  • 34
  • 1
    Nice and straightforward using streams :). just in case someone has issues converting String to int, you can use `mapToObj()` in replacement of `map()` – Tcheutchoua Steve Mar 25 '21 at 21:39
1

Another one liner to achieve this, by splitting the String into String[] of characters and joining them by space:

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

Output: a b c d e

Edit: The above code won't work for strings with Unicode codepoints like "ab", so instead of splitting on empty string, the split should be performed on regex: "(?<=.)".

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

Thanks to @saka1029 for pointing this out.

Osama A.Rehman
  • 912
  • 1
  • 6
  • 12
  • `"ab"` → `" ? ? a b ? ? "`. You should use regex `"(?<=.)"` instead of `""` –  Mar 25 '21 at 20:41
0

You can use Collectors.joining(delimiter,prefix,suffix) method with three parameters:

String s1 = "abcde";

String s2 = Arrays.stream(s1.split(""))
        .collect(Collectors.joining("_+_", "-{", "}-"));

System.out.println(s2); // -{a_+_b_+_c_+_d_+_e}-

See also: How to get all possible combinations from two arrays?