1

I'm trying to replace a String space with an increment integer the String looks like this (for example):

String str = "Im beginner Java Developer "

how can I solve it to be

im1beginner2Java3Developer4

I try str.replace but the problem how I can put it in the String parameter function (replace)

MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
  • A `for-loop` and `StringBuffer` come to find – MadProgrammer Jan 10 '16 at 22:53
  • You won't be able to do this with regex [see this](http://stackoverflow.com/q/10892276/1743880). A simple way is a loop with a `StringBuilder`. Could you post what you have tried? – Tunaki Jan 10 '16 at 22:56

3 Answers3

2

Not the most efficient solution, but possibly the clearest:

String str = "Im beginner Java Developer ";
int count = 0;
while (str.contains(" "))
    str = str.replaceFirst(" ", String.valueOf(++count));
shmosel
  • 45,768
  • 6
  • 62
  • 130
1

You can do the following :

    String str = "Im beginner Java Developer ";

    int index = str.indexOf(" ", 0);
    int count = 1;
    StringBuilder strbild = new StringBuilder(str);
    while (index != -1) {

        strbild.replace(index, index + 1, String.valueOf(count));
        index = str.indexOf(" ", index + 1);
        count++;
    }

    System.out.println(strbild);

Use StringBulider to replace the the elements of the String.

Ahmad Al-Kurdi
  • 2,092
  • 2
  • 19
  • 36
0

If you can use Java 8

    String str = "Im beginner Java Developer ";
    String[] splitted = str.split("\\s+", -1);
    String result = IntStream.range(0, splitted.length)
        .mapToObj(i -> i + splitted[i])
        .collect(Collectors.joining()).substring(1);
    System.out.println(result);