-4

So I am asking for a string to be inputted, then I am asking what the user wants to do to the string, in this case, I am trying to replace the first occurrence of a character. I can ask for what wants to be replaced and what to replace it with. I also know how to do the replacement somewhat, but say if the string has 2 of the same characters, I get a new String for both

(Change i to o: (input)"Find Dime" --->(output) "Fond Dime" & "Find Dome")

I only need the first one.

else if (UserCommand.equalsIgnoreCase("replace first"))
    {
        System.out.println("Enter the character to replace");
        String Replace = input.next();
        System.out.println("Enter the new character");
        String Replacement = input.next();
        for (int i = 0; i<String.length();i++)
        {
            if (String.charAt(i)==Replace.charAt(0)) 
            {
                StringEdit = String.substring(0,i) + Replacement + String.substring(i + Replace.length());
            }
        }

Output:

Enter the string lump sum Enter the character to replace u Enter the new character o lomp sumlump som

5

1 Answer 1

0

if you only need the first String use

break;

in the if statement

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.