user3101676
user3101676

Reputation: 11

Words in String-How to remove

I am trying to allow the user to remove a word from the string str. For example if they type "Hello my name is john", The output should be "Hello is john". How do i make this happen?

import java.util.*;
class WS7Q2{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        System.out.println("Please enter a sentence");
        String str = in.nextLine();

        int j;

        String[] words = str.split(" "); 
        String firstTwo = words[0] + "  " + words[1]; // first two words
        String lastTwo = words[words.length - 2] + " " + words[words.length - 1];//last two   words 

        System.out.println(str);

    }
}

Upvotes: 1

Views: 90

Answers (3)

Paul Samsotha
Paul Samsotha

Reputation: 209002

Why not just use String#replace()

String hello = "Hello my name is john"

hello = hello.replace("my name", "");

System.out.println(hello);

Upvotes: 1

I am Cavic
I am Cavic

Reputation: 1085

This is how you split the string

String myString = "Hello my name is John";

String str = myString.replace("my name", "");
System.out.println(str);

This will print "Hello is John"

Upvotes: 2

amit
amit

Reputation: 178461

String is immutable in java, you cannot modify the string itself (not easily anyway, can be done using reflection - but it is unadvised).

You can bind a new string to str with minimal changes to your code using something similar to:

str = firstTwo + " " + lastTwo;

Upvotes: 0

Related Questions