How to insert comma in specific index in string using java?

Viewed 41

My problem is that I have a line with multiple usernames and I want to separate each username with a comma. Each username contains first name and last name and also "&" symbol between them.

The first name and last name with same criteria and long for both

I know the way to follow, which is that I have to find the number of letters of the first name (before the symbol "&") and after the symbol I get the same number of letters of the first name (that will be the second name) and therefore I add the comma here.

For Example:

The input line like this:

ramy&hanyfrank&gerry

The output should be like this:

ramy&hany,frank&gerry

======

I tried to implement it, but doesn't work with me as following:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class one {
    public static void main(String[] args) {
        // String inputText = "ramy&hanyfrank&gerry";
        StringBuffer inputText2 = new StringBuffer("ramy&hanyfrank&gerry");
        int usernameLength = 0;
        Pattern pattern = Pattern.compile("&");
        Matcher matcher = pattern.matcher(inputText2);
        boolean found = false;
        while (matcher.find()) {
            System.out.println("I found " + matcher.group() + " starting at index " +
                    matcher.start() + " and ending at index " + matcher.end());

            usernameLength = matcher.start() + matcher.end();
            System.out.println(usernameLength);

            inputText2.insert(usernameLength, ",");
            found = true;
        }
        System.out.println(inputText2);
        if (!found) {
            System.out.println("No match found.");
        }
    }
}
1 Answers

With your code , it would throw index out of bound exception because matcher.start()+matcher.end() is incorrect . It will be out of bound. You need to have last inserted position of , and reduce from it.

You can try below code.

    StringBuffer inputText2 = new StringBuffer("ramy&hanyfrank&gerry");
    int usernameLength = 0;
    Pattern pattern = Pattern.compile("&");
    Matcher matcher = pattern.matcher(inputText2);
    boolean found = false;
    int a= 0;
    while (matcher.find()) {
        System.out.println("I found " + matcher.group() + " starting at index " +
                matcher.start() + " and ending at index " + matcher.end());

        usernameLength = matcher.start()-a+matcher.end();
        System.out.println(usernameLength);
        if (usernameLength<inputText2.length())
        inputText2.insert(usernameLength, ",");
        a= usernameLength+1;
        System.out.println(inputText2);
        found = true;
    }
    System.out.println(inputText2);
    if (!found) {
        System.out.println("No match found.");
    }
Related