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(" +", " ");
}
}
Related
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();
}
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) + " ");
}
}
I am trying to return a word in a sentence that has the most common characters with a given string.
For instance:
Given sentence:
Old man sneezed at Starbucks.
Given word:
nee
I want to return sneezed word in that sentence.
I am pretty new to Java and I am actually JS and Python developer so I got really confused with Char array, ArrayList, StringBuilder etc.
In my opinion,
I need to pass given sentence into a String array
Convert each element to char array
Convert given word to char array in the same loop
Count most occuring word and return that index
But I really don't know what array types I need to use.
Can somebody help me out with a little snippet or algorithm that can lead me the path to solution.
This is how I started but I don't feel like this is going to help me out to accomplish what I am looking for:
ArrayList<String> wordArrayList = new ArrayList<String>();
int count = 0;
for(String eachWord : sentence.split(" ")) {
wordArrayList.add(eachWord);
char[] charArray = eachWord.toCharArray();
char[] givenWord = word.toCharArray();
}
Thank you all for your time and attention.
Edit:
I wanted add another case for it to clarify what I am trying to accomplish:
Given sentence:
Up to dubs
Given word:
bus
return:
dubs
Assuming you only want to return the first occurrence, you could modify your for loop to iterate over the whole words in the sentence rather than individual chars by using str.split(), and making use of str.contains():.
class Main {
static String findWordThatMatchesSubString(String sentence, String subString) {
for (String word : sentence.split(" ")) {
if (word.contains(subString)) {
return word;
}
}
return null;
}
public static void main(String[] args) {
String sentence = "Old man sneezed at Starbucks.";
String subString = "nee";
String foundWord = findWordThatMatchesSubString(sentence, subString);
if (foundWord != null) {
System.out.println(foundWord);
} else {
System.out.println(subString + " was not found in any word.");
}
}
}
Output:
sneezed
If you do need to deal with more than one match then using an ArrayList like what you are currently doing would be appropriate:
import java.util.ArrayList;
import java.util.List;
class Main {
static List<String> findWordsThatMatchesSubString(String sentence, String subString) {
List<String> wordMatches = new ArrayList<>();
for (String word : sentence.split(" ")) {
if (word.contains(subString)) {
wordMatches.add(word);
}
}
return wordMatches.size() > 0 ? wordMatches : null;
}
public static void main(String[] args) {
String sentence = "Old man sneezed at Starbucks and dropped his knitting needle on the floor.";
String subString = "nee";
List<String> foundWords = findWordsThatMatchesSubString(sentence, subString);
if (foundWords != null) {
System.out.println(foundWords);
} else {
System.out.println(subString + " was not found in any word.");
}
}
}
Output:
[sneezed, needle]
Regarding your followup question about finding the words in the sentence that have all the characters in the subString you can maintain a Map of Characters and their counts to achieve your desired your result:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Main {
static List<String> findWordsThatContainAllCharsInSubString(String sentence, String subString) {
List<String> wordMatches = new ArrayList<>();
for (String word : sentence.split(" ")) {
if (containsAllChars(word, subString)) {
wordMatches.add(word);
}
}
return wordMatches.size() > 0 ? wordMatches : null;
}
static boolean containsAllChars(String word, String subString) {
if (word.length() < subString.length()) {
return false;
}
Map<Character, Integer> subStringCharsMap = new HashMap<>();
for (char c : subString.toCharArray()) {
subStringCharsMap.put(c, subStringCharsMap.getOrDefault(c, 0) + 1);
}
for (char c : word.toCharArray()) {
if (subStringCharsMap.containsKey(c)) {
if (subStringCharsMap.get(c) == 1) {
subStringCharsMap.remove(c);
} else {
subStringCharsMap.put(c, subStringCharsMap.get(c) - 1);
}
}
if (subStringCharsMap.size() == 0) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String sentence = "I got a new pair of shoes";
String subString = "hes";
List<String> foundWords = findWordsThatContainAllCharsInSubString(sentence, subString);
if (foundWords != null) {
System.out.println(foundWords);
} else {
System.out.println(subString + " was not found in any word.");
}
}
}
Output:
[shoes]
What you have is a good start - it should be possible to iterate over each word after splitting the sentence and then collect either the first / all words that contain the given word.
List<String> wordArrayList = new ArrayList<String>();
String givenWord = // from user
for(String eachWord : sentence.split(" ")) {
if (eachWord.contains(givenWord)) {
wordArrayList.add(eachWord)
}
}
This would then return a list of all words containing the given word. Depending on the requirements this could be changed to startsWith / endsWith etc.
Since you're new to Java I assume you haven't come across the Stream API Another interesting way of doing this:
String givenWord = // from user
List<String> wordArrayList = sentence.split(" ").stream.filter(str -> str.contains(givenWord)).collect(Collectors.toList())
You could just use the contains() method of string class. It takes one argument that is to be searched in the string object. Below code might help.
import java.util.*;
public class Sample{
public static void main(String []args){
ArrayList<String> occurences = new ArrayList<>();
String input = "Old man sneezed at Starbucks.";
String find = "nee";
for(String eachString: input.split(" ")){
if(eachString.contains(find)){
occurences.add(eachString);
}
}
System.out.println(occurences);
}
}
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
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());
}