-4

Got String which contains two symbols:

String s = "AB";

How to add space " " between?

oguz ismail
  • 1
  • 16
  • 47
  • 69
Dartweiler
  • 85
  • 8
  • 4
    I would advise to not just find the answer here, as this is so trivial it only is meant to be solved without help. Just think about it a bit, as it will help you down the road. The general idea is to target each part of the string, then add a space in between the two targets. Try to look up how to do each individual part, and solve it yourself. If you just get the answer, then this exercise will have not helped. – Javoid Jan 02 '21 at 19:02

3 Answers3

0

A String is immutable which means you can't change it, so you need to create a new String.

One way to do this is to use a StringBuilder:

  1. create the StringBuilder using the original string
  2. use the StringBuilder.insert(...) method to insert a character
  3. create a new String using the toString() method of the StringBuilder.
camickr
  • 321,443
  • 19
  • 166
  • 288
0

You can go with something like: s = s.charAt(0) + " " + s.charAt(1);

salam
  • 76
  • 6
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 = "AB";
        s = String.join(" ", s.split(""));
        System.out.println(s);
    }
}

Output:

A B
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110