Java Program to Delete Words from String
Write a Java Program to Remove or Delete Words from String using Inbuilt Function. For delete any particular word from the string in Java Programming, first, you have to ask to the user to enter the string,then second ask to enter the any word present in the string to delete that word from the string.
After asking the two, now check for the presence of that word and perform the deletion of that word from the sentence as shown in the following program.
Example –
Sample Input– This is the sample input from the user.
Word to be deleted– the
Sample Output– This is sample input from user.
This method is shortcut method that uses the method replaceAll( ) to replace all the words with no-space from the string then copy that string into another string without having any that particular words.
Java String replaceAll() :
The java string replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
Syntax :
public String replaceAll(String regex, String replacement)
Parameters
- regex — This is the regular expression to which this string is to be matched.
- replacement — This is the string to be substituted for each match.
Return Value
This method returns the resulting string.
Following Java program removes all the words present in the string using inbuilt function.We use the function named replaceAll() to remove or delete all the words from the string.
Here is source code of the Java Program to remove given word from a string. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
SOURCE CODE ::
import java.util.Scanner; public class delete_Words { public static void main(String args[]) { String str1, str2; Scanner scan = new Scanner(System.in); System.out.print("Enter any String : "); str1 = scan.nextLine(); System.out.print("Word to Delete from String [ " +str1+" ]: "); str2 = scan.nextLine(); System.out.print("Deleting all '" + str2 + "' from '" + str1 + "'------->\n"); str1 = str1.replaceAll(str2, ""); System.out.println("\nAfter Deletion, Reqd. String is : [ "+str1+" ]"); } }
OUTPUT : :
Enter any String : Hello Codez Club Word to Delete from String [ Hello Codez Club ]: Codez Deleting all 'Codez' from 'Hello Codez Club'-------> After Deletion, Reqd. String is : [ Hello Club ]