Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. // Java program to remove
  2. // a given word from a string
  3. import java.util.Scanner;
  4.  
  5.  
  6. public class Program7 {
  7. public static String removeWord(String string, String word)
  8. {
  9.  
  10.  
  11. // Check if the word is present in string
  12. // If found, remove it using removeAll()
  13. if (string.contains(word)) {
  14.  
  15. // To cover the case
  16. // if the word is at the
  17. // beginning of the string
  18. // or anywhere in the middle
  19. String tempWord = word + " ";
  20. string = string.replaceAll(tempWord, "");
  21.  
  22. // To cover the edge case
  23. // if the word is at the
  24. // end of the string
  25. tempWord = " " + word;
  26. string = string.replaceAll(tempWord, "");
  27. }
  28.  
  29. // Return the resultant string
  30. return string;
  31. }
  32.  
  33. public static void main(String args[])
  34. {
  35.  
  36. Scanner sc = new Scanner(System.in);
  37. System.out.println("Enter a sentence: ");
  38. String string = sc.nextLine();
  39.  
  40. System.out.println("Enter a word: ");
  41. String word = sc.next();
  42. // Test case 1
  43. System.out.println( removeWord(string, word));
  44.  
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement