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
  • 343,457
  • 22
  • 230
  • 366
  • 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
  • 49,289
  • 6
  • 73
  • 138
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,248
  • 3
  • 23
  • 39
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);