从字符串中删除给定单词的Java程序
给定一个字符串和一个单词,该任务从字符串删除该单词(如果它存在),否则返回 -1 作为输出。为了更清楚,请查看下面给出的插图,如下所示。
插图:
Input : This is the Geeks For Geeks
word="the"
Output : This is Geeks For Geeks
Input : Hello world Hello"
word = Hello
Output : world
Explanation: The given string contains the word two times
Input : Hello world
word = GFG
Output : Hello world
Explanation: word doesn't exists in the string
现在为了达到目标,我们将讨论以下两种方法:
- 使用搜索技术的朴素方法
- 使用 String.replaceAll() 方法的最佳方法
方法 1:使用搜索技术
- 将字符串转换为字符串数组。
- 迭代数组并检查不等于给定单词的单词。
- 将单词连接成一个新的字符串数组 name 作为一个新的字符串。
- 打印新字符串。
例子
Java
// Java Program to Remove a Given Word From a String
// using searching techniques
// Importing input output classes
import java.io.*;
// main class
class GFG {
// Method 1
// To remove the word
static void remove(String str, String word)
{
// Split the string using split() method
String msg[] = str.split(" ");
String new_str = "";
// Itearating the string using for each loop
for (String words : msg) {
// If desired word is found
if (!words.equals(word)) {
// Concate the word not equal to the given
// word
new_str += words + " ";
}
}
// Print the new String
System.out.print(new_str);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom string as input
String str = "This is the Geeks For Geeks";
// Word to be removed from above string
String word = "the";
// Calling the method 1 by passing both strings to
// it
remove(str, word);
}
}
Java
// Java Program to Remove a Given Word From a String
// Importing input output classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Given String as input from which
// word has to be removed
String str = "This is the Geeks For Geeks";
// Desired word to be removed
String word = "the";
// Replace all words by "" string
// using replaceAll() method
str = str.replaceAll("the", "");
// Trim the string using trim() method
str = str.trim();
// Printing the final string
System.out.print(str);
}
}
输出
This is Geeks For Geeks
方法二:使用 String.replaceAll() 方法
- 这个方法需要两个输入 old_word 和正则表达式格式的新词。
- 用新词替换所有 old_word。
- 返回结果字符串。
例子
Java
// Java Program to Remove a Given Word From a String
// Importing input output classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Given String as input from which
// word has to be removed
String str = "This is the Geeks For Geeks";
// Desired word to be removed
String word = "the";
// Replace all words by "" string
// using replaceAll() method
str = str.replaceAll("the", "");
// Trim the string using trim() method
str = str.trim();
// Printing the final string
System.out.print(str);
}
}
输出
This is Geeks For Geeks