Question

Ok, so I am required to create a program that will replace a word in a string according to a string, and also given a replacement. (In this case replace UK with United Kingdom)

Below is my code, but it doesn't work

import java.util.*;
public class replace
{
    public static void main(String[]args){
        replace("The UK should not be written as uk", "UK", "United Kingdom");
    }

    static void replace(String input, String seed, String replacement){
        String s = "";
        ArrayList<String> bla = new ArrayList<String>();
        for(int i = 0; i < input.length();i++){
            if(input.charAt(i) != ' '){
                s = s + input.charAt(i);
            }
            if(input.charAt(i) == ' ' || i+1 == input.length()){
                bla.add(s);
                s = "";
            }
        }

        String out = "";
        for(int i = 0; i < bla.size(); i++){
            if(bla.get(i) == seed){
                bla.set(i, replacement);
            }
        }

        for(int i = 0; i < bla.size(); i++){
            out = out + bla.get(i)+ " ";
        }

        System.out.println(out);

   }
}

For some reason it's not replacing my variable with the replacement

 String out = "";
            for(int i = 0; i < bla.size(); i++){
                if(bla.get(i) == seed){
                    bla.set(i, replacement);
                }
            }

Any ideas why this might be?

Thanks in advance

Was it helpful?

Solution

Replace:

if(bla.get(i) == seed)

With:

if(bla.get(i).equals(seed))

The first compares reference, the second equality.

You should also use a StringBuilder to concatanate Strings, and keep it inside the loop:

ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length(); i++) {
    StringBuilder s = new StringBuilder();

    if(input.charAt(i) != ' ')
        s.append(input.charAt(i));

    if(input.charAt(i) == ' ' || i+1 == input.length())
        bla.add(s.toString());
}

Using a StringBuilder is more efficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top