-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

Pluto
  • 1
  • 1
  • 3
    Call `String.toCharArray()` then change the array. Then convert this char array back to String. – xingbin Oct 06 '18 at 16:18
  • 1
    First, what is the `String` you want to replace from? It's not named `String`. – Elliott Frisch Oct 06 '18 at 16:18
  • See this https://stackoverflow.com/questions/20656523/replace-characters-in-a-string-without-using-string-replace-method – flyingfox Oct 06 '18 at 16:19
  • 1
    Possible duplicate of [Replace characters in a string, without using string replace() method](https://stackoverflow.com/questions/20656523/replace-characters-in-a-string-without-using-string-replace-method) – Nicholas K Oct 06 '18 at 16:19
  • http://idownvotedbecau.se/noresearch/, e.g. web search for question title: [`How to replace character in string without using the replace function in Java`](https://www.google.com/search?q=How+to+replace+character+in+string+without+using+the+replace+function+in+Java) – Andreas Oct 06 '18 at 16:22

1 Answers1

0

if you only need the first String use

break;

in the if statement