Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Java program to remove
- // a given word from a string
- import java.util.Scanner;
- public class Program7 {
- public static String removeWord(String string, String word)
- {
- // Check if the word is present in string
- // If found, remove it using removeAll()
- if (string.contains(word)) {
- // To cover the case
- // if the word is at the
- // beginning of the string
- // or anywhere in the middle
- String tempWord = word + " ";
- string = string.replaceAll(tempWord, "");
- // To cover the edge case
- // if the word is at the
- // end of the string
- tempWord = " " + word;
- string = string.replaceAll(tempWord, "");
- }
- // Return the resultant string
- return string;
- }
- public static void main(String args[])
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter a sentence: ");
- String string = sc.nextLine();
- System.out.println("Enter a word: ");
- String word = sc.next();
- // Test case 1
- System.out.println( removeWord(string, word));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement