简体   繁体   中英

Java - Adding Asterisks between a user inputted string

I'm working on a class assignment with a few individual parts, which I have all done with the exception of this one. I need to get a string input from the user and create a loop (preferably a for loop) that inserts asterisks between each character. I'm completely stumped on this one so if someone could just give me some help to get started it would be appreciated.

Edit: I've come up with this so far

    } else if (choice.equalsIgnoreCase("C")) {
        System.out.print("Enter text here: ");
        String orig = input.nextLine();

        // To use for asterisk insertion
        int x = 1;
        int y = 2;

        for (int length = orig.length(); length > 0;) {
            orig = orig.substring(0,x) + "*" + orig.substring(y);
            x = x + 2;
            y = y + 2;
        }

    } 

It compiles just fine but when I test it and enter some text it comes up with Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

You could use a for loop on the characters of the String (see below), but I would just do this:

str = str.replaceAll("(?<=.)(?=.)", "*");

The regex in the search parameter matches the point between any two characters, achieved by using a look-behind and a look-ahead, each asserting that there's a character there.


If you must use a loop, the simplest code is probably:

String result = input.isEmpty() ? "" : input.substring(0, 1);
for (int i = 1; i < input.length(); i++)
    result += "*" + input.charAt(i);

The somewhat complicated first line caters for the edge case of the user entering a blank. The for loop already caters for blank input, because the terminating condition will always be false for blank, so it won't iterate at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM