Home > front end >  How to replace comma with New line number in Java?
How to replace comma with New line number in Java?

Time:07-20

I need to replace every comma in a string to new line with number in it.

String str = "Peter, Bob, Chester, Mike";

I have done for replacing comma with new line.

str = str.replace(",", "\n");

This give me output like this

Peter
Bob
Chester
Mike

What I'm wanted to do is

1. Peter
2. Bob
3. Chester
4. Mike

*The requirement need string not a array.

CodePudding user response:

Try to patching the result. Spilt str to array, and then map it, and collect it in the end

AtomicInteger counter = new AtomicInteger(1);
String ret = Arrays.stream(s.split(","))
    .map(e -> counter.getAndIncrement()   ". "   e.trim())
    .collect(Collectors.joining("\n"));

CodePudding user response:

you can use the split (which splits the String into a string array) method like so and use a forEach loop:

    int counter=0;

    for(String s:str.split(",")){
        System.out.println(counter ". " s);
        counter  ;
    }

Hope it helps.

CodePudding user response:

You can't just use replace, because you also need the enumerate the names, I think a simple (but not the shortest or elegant solution is to use a for loop.

Hope it helped.

    String str = "Peter, Bob, Chester, Mike";
    String[] names = str.split(",");

    StringBuilder sb = new StringBuilder();
    // iterate through every name
    for (int i = 0; i < names.length; i  ) {
        // put the number before each name
        // trim method removes all white spaces which where left over from split
        sb.append((i 1)   ". "   names[i].trim());

        // if it isn't the last name, add an newline
        if (i != names.length -1 ) {
            sb.append("\n");
        }
    }

    System.out.println(sb.toString());

CodePudding user response:

From your data, it looks like that actual separator is ", " rather than just ",". Then you don't have to trim each name. And each name should end with a newline.

var names = str.split(", ");
var namesNumberedLines = IntStream.range(0, names.length)
    .mapToObj(i -> (i   1)   ". "   names[i]   System.lineSeparator())
    .collect(Collectors.joining());
  •  Tags:  
  • java
  • Related