Reverse individual words in a Java String - java

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());
}

Related

How to remove multiple words 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.
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();
}

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 separate a String line with a paragraph to make text as a list

I have a really long text that looks like "123testes1233iambeginnerplshelp123 .." and I need to separate the line with the paragraph each time the program reads number.
So output should be like:
123tests
12333iambeninnerplshelp
123 ...
You can solve it using Regex. Everytime we are looking for patterns where number is followed by characters and if it is found, print it:
String text = "123testes1233stackoverflowwillsaveyou123dontworry";
String wordToFind = "\\d+[a-z]+";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println(match.group());
}
One way to do it would be to use StringTokenizer. If you make the assumption that every output line must start with 123, even if the input doesn't start with it, it could be:
String input = "123testes1233iambeginnerplshelp123 ..";
String delimiter = "123";
StringTokenizer tokenizer = new StringTokenizer(input, delimiter);
while (tokenizer.hasMoreTokens()) {
String line = delimiter + tokenizer.nextToken();
System.out.println(line);
}
A simple approach (without any dependencies) would look something like this,
class Test {
public static void main (String[] args) throws java.lang.Exception
{
String a = "123testes1233iambeginnerplshelp123";
StringBuffer sb = new StringBuffer();
for (int i=0; i<a.length()-1; i++) {
while (i<a.length()-1 && !(!isNumber(a.charAt(i)) && isNumber(a.charAt(i+1)))) {
sb.append(a.substring(i,i+1));
i++;
}
sb.append(a.substring(i,i+1));
System.out.println(sb.toString());
sb.setLength(0);
}
}
private static boolean isNumber (char c) {
return ((int)c >=48) && ((int)c <= 57);
}
}
my solution
public StringSplitNum(){
String someString = "123testes1233iambeginnerplshelp123abc";
String regex = "((?<=[a-zA-Z])(?=[0-9]))|((?<=[0-9])(?=[a-zA-Z]))";
List arr = Arrays.asList(someString.split(regex));
for(int i=0; i< arr.size();i+=2){
System.out.println(arr.get(i)+ " " + arr.get(i+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

Categories

Resources