How to remove multiple words from a string Java - java

I'm new to java and currently, I'm learning strings.
How to remove multiple words from a string?
I would be glad for any hint.
class WordDeleterTest {
public static void main(String[] args) {
WordDeleter wordDeleter = new WordDeleter();
// Hello
System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));
// The Athens in
System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));
}
}
class WordDeleter {
public String remove(String phrase, String[] words) {
String[] array = phrase.split(" ");
String word = "";
String result = "";
for (int i = 0; i < words.length; i++) {
word += words[i];
}
for (String newWords : array) {
if (!newWords.equals(word)) {
result += newWords + " ";
}
}
return result.trim();
}
}
Output:
Hello
The Athens is in Greece
I've already tried to use replacе here, but it didn't work.

You can do it using streams:
String phrase = ...;
List<String> wordsToRemove = ...;
String result = Arrays.stream(phrase.split("\s+"))
.filter(w -> !wordsToRemove.contains(w))
.collect(Collectors.joining(" "));

Programmers often do this:
String sentence = "Hello Java World!";
sentence.replace("Java", "");
System.out.println(sentence);
=> Hello Java World
Strings are immutable, and the replace function returns a new string object. So instead write
String sentence = "Hello Java World!";
sentence = sentence.replace("Java", "");
System.out.println(sentence);
=> Hello World!
(the whitespace still exists)
With that, your replace function could look like
public String remove(String phrase, String[] words) {
String result = phrase;
for (String word: words) {
result = result.replace(word, "").replace(" ", " ");
}
return result.trim();
}

Related

In the text, words of a given length are replaced by a specified substring of arbitrary length

I need to replace all words given length by random substring of arbitraty lenght.For example, the length given word is 3, thus i need to replace "the" to "a"
String str = "Java is the best language in the world!";
String randomWord = "a";
//Manipulations
System.out.println(str);
// Outputs: Java is a best language in a world!
An algorithm like this should work:
String str = "Java is the best language in the world!";
String randomWord = "a";
int givenLength = 3;
// Split the string into an array containing each word:
String arr[] = str.split(" ");
// Loop through and find & replace all words of the given length
for (int i=0; i<arr.length; i++){
if (arr[i].length() == givenLength) {
arr[i] = randomWord;
}
}
// Rejoin words into a new string
String output = String.join(" ",arr);
public static void main(String[] args) {
String str = "Java is the best language in the world!";
int wordLength = 3;
String replaceWord = "a";
Function<String, String> replaceFunction = element -> {
if (element.toCharArray().length == wordLength) {
return replaceWord;
} else {
return element;
}
};
String result = Arrays.stream(str.split(" "))
.toList()
.stream()
.map(replaceFunction)
.collect(Collectors.joining(" "));
System.out.println(result);
}

How to remove multiple words, Not replace!, from a string Java

I'm new to java and currently I'm learning strings.
How to remove multiple words from a string? I would be glad for any hint.
The replacement doesn't work as it deletes a part of a word.
class WordDeleterTest {
public static void main(String[] args) {
WordDeleter wordDeleter = new WordDeleter();
// Hello
System.out.println(wordDeleter.remove("Hello Java", new String[] { "Java" }));
// The Athens in
System.out.println(wordDeleter.remove("The Athens is in Greece", new String[] { "is", "Greece" }));
// This cat
System.out.println(wordDeleter.remove("This is cat", new String[] { "is" }));
}
}
class WordDeleter {
public String remove(String phrase, String[] words) {
String result = phrase;
for (String word : words) {
result = result.replace(word, "");
}
return result.trim();
}
}
Output:
Hello
The Athens in
Th cat
Consider using replace or replaceAll with regexp
public static void main(String[] args) {
String originalstring = "This is cat";
System.out.println ("Original String: " + originalstring);
System.out.println ("Modified String: " + originalstring.replaceAll("\\s(is)", ""));
}
\\s(is) represents that all fragment space + is
ReplaceAll uses a regex so you do not need a loop. Instead make an or regex out of the words array.
result = phrase.replaceAll("\\W("+String.join("|", words)+")\\W","");
class WordDeleter {
public String remove(String phrase, String[] words) {
String result = phrase;
for (String word : words) {
result = result.replaceAll("\\b" + word + "\\b", "");
}
return result.trim().replaceAll(" +", " ");
}
}

Reverse a string word by word except the last letter of each word

I'd like to reverse a string word by word except the last letter of each word.
For example: "Hello how are you" -> lleHo ohw rae oyu
but I am getting output as: olleH woh era uoy
I'm not able to fix the last letter of each word.
This is my Java code for the above output:
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
for(int j=i;j>=pos;j--)
{
System.out.print(ch[j]);
}
pos=i+1;
}
}
}
}
Below is the solution to solve the problem:
public class Main {
public static void main(String[] args) {
//call the reverseSentence Method
reverseSentence("Hello how are you");
}
public static void reverseSentence(String sentence) {
//Replacing multiple space with a single space
sentence = sentence.replaceAll("[ ]{2,}", " ");
//Split the array and store in an array
String [] arr = sentence.split(" ");
StringBuilder finalString = new StringBuilder();
//Iterate through the array using forEach loop
for(String str : arr) {
//Creating substring of the word, leaving the last letter
String s = str.substring(0, str.length() - 1);
//Creating StringBuilder object and reversing the String
StringBuilder sb = new StringBuilder(s);
//Reversing the string and adding the last letter of the work again.
s = sb.reverse().toString() + str.charAt(str.length() - 1);
//Merging it with the final result
finalString.append(s).append(" ");
}
//Printing the final result
System.out.println(finalString.toString().trim());
}
}
What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.
I'd use regex replaceAll with a lambda to handle the reversal. \S+ matches any sequence of non-space characters. This has the advantage of elegantly handling arbitrary whitespace. You could use \w+ if you want to avoid reversing punctuation characters, although matching words like "isn't" and so forth suggests the problem devolves into natural language processing. I assume your specification is not so complex, though.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String res = Pattern
.compile("\\S+")
.matcher("Hello how are you")
.replaceAll(m -> {
String s = m.group();
return new StringBuilder(s.substring(0, s.length() - 1))
.reverse().toString() + s.charAt(s.length() - 1);
});
System.out.println(res); // => lleHo ohw rae oyu
}
}
How do you think of this solution?
public class Main
{
public static void main(String[] args) {
String s = "Hello how are you ";
char [] ch = s.toCharArray();
System.out.println(ch.length);
int pos=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==' ')
{
System.out.print(ch[i]);
for(int j=i-2;j>=pos;j--)
{
System.out.print(ch[j]);
}
System.out.print(ch[i-1]);
pos=i+1;
}
}
}
}
public class Main {
public static void main(String[] args) {
String s = "Hello how are you ";
final List<String> list = Arrays.asList(s.split(" "));
StringBuilder builder = new StringBuilder();
list.forEach(item ->{
StringBuilder itemBuilder = new StringBuilder(item);
final String rStr = itemBuilder.reverse().toString();
builder.append(rStr.substring(1,rStr.length())).append(rStr.substring(0,1)).append(" ");
});
System.out.println(builder.toString());
}
}
FP style:
String str = "Hello how are you";
String res = Arrays.stream(str.split(" "))
.map(s ->
new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString() + s.substring(s.length() - 1)
)
.reduce((s, s1) -> s + " " + s1)
.orElse("");
System.out.println(res); // lleHo ohw rae oyu
A simpler solution would be to just use the Java Stack data structure for each word (after a string.split) and just add each letter (except token.length-1).
public static void main(String[] args) {
String string = "Hello how are you ";
final String[] tokens = string.split(" ");
for (String token : tokens) {
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < token.length()-1; i++) {
stack.push(token.charAt(i));
}
while (!stack.empty()) {
System.out.print(stack.pop());
}
System.out.print(token.charAt(token.length()-1) + " ");
}
}

how to reverse the word using list iterator in java

class StringRev{
public static void main(String args[]){
String str = "He is the one";
String temp = "";
String finalString = "";
for(int i =str.length()-1;i>=0;i--){
temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
if(str.charAt(i) == ' '||i==0){
for(int j=temp.length()-1;j>=0;j--){
finalString += temp.charAt(j);
}
temp = "";
}
}
System.out.println(finalString);
}
}
I tried to solve.I have to reverse the string "He is the one" to "one the is He".
I have written some programs in Java but am looking for other best solutions.
Suggest any possible ways to minimize the current.
Split the String into words and the iterate downwards and append the words back to a String.
public class StringRev{
public static void main(String args[]){
String input = "He is the one";
String output = "";
String[] inputSplit = input.split(" ");
for(int i=inputSplit.length-1; i>=0; i--){
output += inputSplit[i] + " ";
}
System.out.println(output.trim()); //remove trailing space
}
}
If you can use Collections and StringUtil then it's even more straight forward.
public class StringRev{
public static void main(String args[]){
String input = "He is the one";
String[] inputSplit = input.split(" ");
Collections.reverse(Arrays.asList(inputSplit));
String output = StringUtil.join(Arrays.asList(inputSplit), " ");
System.out.println(output);
}
}
Simply just split given string on spaces, will give you an array of words, iterate reversely and append it to new string as following:
String string = "He is the one";
System.out.println("Original String: " + string);
String[] arr = string.split(" ");
String reverseString = "";
for(int i = arr.length - 1; i >= 0; i--){
reverseString += arr[i] + " ";
}
System.out.println("Reverse String: " + reverseString);
OR you can use Arrays utility to convert split-ed string into List, make it reverse it using Collection utility reverse method, iterate over it and create string as following:
List<String> list = Arrays.asList(string.split(" "));
Collections.reverse(list);
String reserveStringUsingList = "";
for(String str : list){
reserveStringUsingList += str + " ";
}
System.out.println("Reverse String using List: " + reserveStringUsingList);
Here is the solution you asked for, using ListIterator:
Code:
public static void main(String[] args) {
final String str = "He is the one";
System.out.println(str);
System.out.println(reverseWords(str));
}
static String reverseWords(String str) {
StringBuilder result = new StringBuilder(str.length());
List<String> words = Arrays.asList(str.split(" "));
if(!words.isEmpty()) {
ListIterator<String> it = words.listIterator(words.size());
result.append(it.previous());
while (it.hasPrevious()) {
result.append(' ').append(it.previous());
}
}
return result.toString();
}
Output:
He is the one
one the is He

Reverse individual words in a Java String

I am trying to reverse text in a given string. The problem I am having with my code below is that when I enter something like "Hey man" it prints out "nam yeH" Whereas I want it to print out "yeH nam". Is there any help you could give me that could fix this mistake?
Thanks so much in advance!
public class ReverseWords {
public static void main(String[] args) {
String text;
text = IO.readString();
int plusIndex = text.indexOf("+");
if ( plusIndex != -1 ) {
IO.reportBadInput();
System.exit(0);
}
IO.outputStringAnswer(new StringBuilder(text).reverse().toString());
}
}
Split the input on the space character, then loop through the array of words, reverse them, and piece them back into a new string.
private String reverseWords(String text) {
String result = "";
String[] words = text.split(" ");
StringBuilder builder;
for (String word : words) {
builder = new StringBuilder(word);
result = result + " " + builder.reverse().toString();
)
return result.replaceFirst(" ", "");
}
reverseWords("hey man"); //should return "yeh nam"
Use a StringTokenizer to tokenize words, and then reverse word by word, and sum it up in a String by adding missing blanks.
Something like this:
public static void main(String[] args) {
String s = "Hey man";
System.out.println(new StringBuilder(s).reverse());
StringTokenizer st = new StringTokenizer(s, " ");
StringBuilder sb = new StringBuilder();
while (st.hasMoreTokens()) {
sb.append(new StringBuilder(st.nextToken()).reverse());
if (st.hasMoreTokens()) {
sb.append(" ");
}
}
System.out.println(sb.toString());
}

Categories

Resources