简体   繁体   中英

Removing words from a String (while using specific methods)

I want to remove all instances of 1 specific word ("STOP") from a given String. I need to accomplish this by first splitting the String

This is what I've got so far:

public static String telegram(String sentence)
    {
        String[] words = sentence.split(" ");
        for(int i = 0; i < words.length; i++)
        {
            if(words[i].equals("STOP"))
            {
                ...
            }
        }

    }

How do I go about removing the words? I've tried using the for loop and making the Array element with the word null, but I'm not sure if that'll work.

I need to use the methods append(String) and toString() and I'm not sure how to use these.

Thanks in advance!

if you have to do this with the split method you would want something like this.

public static String telegram(String sentence)
{
    String[] words = sentence.split(" ");
    StringBuilder result= new StringBuilder();
    for(int i = 0; i < words.length; i++)
    {
        if(!words[i].equals("STOP"))
        {
            result.append(words[i]);
            result.append(" ");
        }
    }
  return result.toString();

}

if you dont have to use slip i would suggest using the replace all method, make your code simpler.

If all you want is using append and toString you can do this

            public static String telegram(String sentence) {
                String[] words = sentence.split("STOP");
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < words.length; i++) {
                    builder.append(words[i]);
                }
                return builder.toString();

            }

Try to replace it by sentence = String.replaceAll("STOP","");

EDIT: Sorry misunderstanding

Use StringBuilder as recommended

First of all, technically, you can't remove words from a String. In Java, Strings are immutable. What you probably want to do then, is to create a new String exactly like the original except that the word "STOP" is removed.

You can do this fairly easily by using String.replaceAll ( JavaDoc ). In fact, the method could be this short:

return sentence.replaceAll("STOP", "");

EDIT: Sorry, I didn't notice that you had constraints on the methods you had to use.

You might want to take a look at StringBuilder. After splitting the String with the delimiter "STOP", you are left with an array of Strings that comprise the message with the stops removed. Then you can use StringBuilder.append ( JavaDoc ) to create a StringBuilder representing the whole message again and then use the StringBuilder's toString() method to return the contents of the StringBuilder as a String.

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