Reversing the words in a sentence string [duplicate] - java

This question already has answers here:
Reverse each individual word of "Hello World" string with Java
(27 answers)
Closed 9 years ago.
So im trying to reverse the words in a sentence like: "Hi dog cat", would become "iH god tac". I was wondering if i can use what im doing to achieve that. I can get the sentence itself to reverse, but i cant get individual words to do so. Is there a way to do this with Strings or do i have to mess with Character(which is confusing too)? Any help is appreciated
private static String PrintStack(String sentence)
{
String reverse = "";
String stringReversed = "";
String Last;
String First;
Stack<String> stack= new Stack<String>();
String words[] = sentence.split(" ");
Last = words[words.length-1];
for(int j = 0; j < words.length; j++)
{
String newWord = words[0+j];
stack.push(newWord);
System.out.println(stack);
}
while(!stack.isEmpty())
{
stringReversed += stack.pop();
}
System.out.println("Reverse is: " + stringReversed);
return reverse;
}
}

FYI in Java it's conventional to name methods and variables with lowercase first letters, e.g., "printStack().
Your algorithm doesn't reverse the words themselves. I'd do it like this:
private static String reverseWords(String sentence) {
String words[] = sentence.split(" ");
ArrayList<String> reversed = new ArrayList<String>();
for (String word : words) {
reversed.add(new StringBuilder(word).reverse().toString());
}
StringBuilder reversedSentence = new StringBuilder();
for (String word : reversed) {
reversedSentence.append(word);
reversedSentence.append(" ");
}
return reversedSentence.toString().trim();
}
Hope this helps,
--Mark

Related

Randomise each element of String from inside? [duplicate]

This question already has answers here:
Randomize the letters in the middle of the word, while keeping the first and last letters unchanged
(5 answers)
Closed 10 months ago.
I am trying to change the place of characters in a string. The first and last have to stay like they are.
For example:
String str = "String test print out";
The output should be for example:
Sirntg tset pirnt out
The first and last character of each word have to stay the rest have to change randomly:
Here is the code I already did, I tried to split the element of the string in an array and split them, but it's not working:
import java.util.*;
public class Main
{
public static void main(String[] args) {
String str = "String test out";
String[] words = str.split("\\s");
Random rnd = new Random();
ArrayList<Integer> digitList = new ArrayList<Integer>();
for(int j = 0;0<=words[].length();j++){
int lst = words[j].length();
char first = words[j].charAt(0);
char last = words[j].charAt(words[j].length() - 1);
for(int i =1, random = 0; i < words[j].length()-1; i++){
do{
random = rnd.nextInt(words[j].length()-2)+1;
}while(digitList.contains(random));
digitList.add(random);
System.out.print(words[j].charAt(random));
}
}
}
}
You could make use of some nifty functionality in Java's collection framework:
public static void main(String[] args) {
String str = "String test out";
for (String word : str.split("\\s")) {
List<Character> chars = word.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
// shuffle the letters in the word, except for the first one and last one
Collections.shuffle(chars.subList(1, chars.size() - 1));
String shuffledWord = chars.stream()
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(shuffledWord);
}
}
Here is a really efficient way to do it. Instead of splitting, changing strings and merging them back together, create a single StringBuilder and use a Pattern to go through each word, scramble them and then return the string.
/** This pattern matches a word, and group 1 excludes the first and last letter. */
static final Pattern WORD = Pattern.compile("\\b\\w(\\w{2,})\\w\\b");
public String scrambleWords(String input) {
Random random = new Random();
StringBuilder s = new StringBuilder(input);
Matcher m = WORD.matcher(input);
while (m.find()) {
int start = m.start(1);
int end = m.end(1);
for (int i = start; i + 1 < end; i++) {
int j = random.nextInt(i + 1, end);
char c1 = s.charAt(i);
char c2 = s.charAt(j);
s.setCharAt(i, c2);
s.setCharAt(j, c1);
}
}
return s.toString();
}

Detect periods in stacks

Hello I am currently working on a program that reverses sentences using stacks. However, I need to implement a function that detects periods and then repeats the loop over again. For example, I could write "Hello my name is blank. nice to meet you." and it would print "you. meet to nice blank. is name my Hello" when I actually just need it to reverse each sentence individually, if that makes sense. So "blank is name my Hello. you meet to nice." is my desired output. Any advice would help greatly, thank you!
import java.util.Stack;
import java.util.Scanner;
public class NolascoStackReverse {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
Stack<String> reverse = new Stack<String>();
System.out.println("Enter a sentence to be reversed: ");
String str = in.nextLine();
String[] wordsArray = str.split(" ");
for (String word : wordsArray) {
reverse.push(word);
}
System.out.println("Here is the reversed order: ");
while (reverse.empty() == false) {
System.out.print(reverse.pop() + " ");
}
}
}
Below code splits your string with space char. You need to split it with period first and split each sentence with space.
String[] wordsArray = str.split(" ");
If you dont care for period, then you can use multiple delimiters for split function :Use String.split() with multiple delimiters
If you need period in reversed sentence, you can use below code:
String[] sentenceArray = str.split(("\\."));
for (String sentence : sentenceArray){
String[] wordsArray = sentence.split((" "));
for (String word : wordsArray) {
reverse.push(word);
}
reverse.push(".");
}
There is already an API available in Java for processing text. You can use BreakIterator like this:
public class Test {
public static void main(String[] args) throws Exception {
Stack<String> reverse = new Stack<String>();
String result="";
Locale enUS = new Locale("en","US");
String str = "My name is R.R.Martin. Nice to meet you.";
System.out.println("Text: " + str);
System.out.print("Here is the reversed order: ");
List<String> sentences = getPieces(str, BreakIterator.getSentenceInstance(enUS));
for(String s : sentences) {
s = s.substring(0,s.length()-1);
List<String> words = getPieces(s, BreakIterator.getWordInstance(enUS));
reverse.clear();
for (String w : words) {
reverse.push(w.strip());
}
while (reverse.empty() == false) {
result += reverse.pop() + " ";
}
result = result.strip();
result += result.length()>0? ". ":"";
}
System.out.println(result);
}
public static List<String> getPieces(String text, BreakIterator bi) {
int boundary,start;
String piece = "";
List<String> list = new ArrayList<>();
bi.setText(text);
boundary = bi.first();
start = 0;
while (boundary != BreakIterator.DONE) {
if(boundary>0)
piece = text.substring(start,boundary);
start = boundary;
boundary = bi.next();
if(!piece.strip().isBlank())
list.add(piece.strip());
}
return list;
}
}
Output:
Text: My name is R.R.Martin. Nice to meet you.
Here is the reversed order: R.R.Martin is name My. you meet to Nice.
Advantage of this approach is that it is locale sensitive i.e. you can use the code with other languages.

Inject character between substring of a string in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a list of words stored in a list, words.
private String[] words = new String[]{"world", "you"};
I then have a string, helloWorld
private String helloWorld = "Hello world how are you?";
I would like to create a function that will take a string (in this case, helloWorld) and it will look case-insensitively to see if any of the strings in the words list are present. If there is, it will put a * character in between each letter of the matching string.
E.g. the output would be
Hello w*o*r*l*d how are y*o*u? since both world and you are in the list.
Passing "Hello" would simply return back the unmodified string "Hello" because there is nothing in the string that is inside words.
How would I go about doing this? I have tried hardcoding a .replaceAll() call on the string for each word, but then I lose the casing of the string. E.g. "Hello world how are you?" became "hello w*o*r*l*d how are y*o*u?"
This code:
private static String[] words = new String[]{"world", "you"};
private static String helloWorld = "Hello world how are you?";
public static String getHello() {
String s = helloWorld;
for (String word : words) {
int index = s.toLowerCase().indexOf(word.toLowerCase());
if (index >= 0) {
String w = s.substring(index, index + word.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, index));
for (int i = 0; i < w.length(); i++) {
sb.append(w.charAt(i));
if (i < w.length() - 1)
sb.append("*");
}
sb.append(s.substring(index + w.length()));
s = sb.toString();
}
}
return s;
}
public static void main(String[] args) {
System.out.println(getHello());
}
prints:
Hello w*o*r*l*d how are y*o*u?
String helloWorld = "hello world how are you ";
String[] words = new String[]{"world", "you"};
String newWord = "";
String words1[]= helloWorld.split(" ");
for (int i = 0;i< words.length;i++){
for (int j=0;j<words1.length;j++){
if (words1[j].equals(words[i])){
for (int k = 0 ; k < words1[j].length(); k++){
char character = words1[j].charAt(k);
newWord+=character;
newWord += "*";
}
words1[j] = newWord;
newWord= "";
}
}
}
String str = Arrays.toString(words1);
System.out.println(str);
}

Java Longest word from inputs

I am a beginner-novice and I am trying to figure out why the logic for finding the largest word doesn't work.
Sometimes the output will result in the correct longest word, the first word, or more than one word.
Thanks!!
PS
I do not really care about the cases if two words of the same length, which I will work later once I figure out why this doesn't work. And once again please note I am a beginner/novice. Thanks
import java.util.Scanner;
import java.util.ArrayList;
public class Word
{
public static String word(String str)
{
int longestCount=0;
int count=0;
int newWord=0;
String theWord="";
ArrayList <String> longestWord= new ArrayList <String>();
for (int i=0; i <str.length(); i++)
{
if (str.substring(i,i+1).equals(" "))
{
if (longestCount<count)
{
longestCount=count;
theWord="";
theWord=""+str.substring(newWord,i);
newWord=i+1;
count=0;
}
}
else
{
count++;
}
}
longestWord.add(theWord);
String output="";
for (int i=0; i<longestWord.size();i++)
output+=longestWord.get(i);
return output;
}
public static void main ()
{
Scanner scan= new Scanner(System.in);
String words= scan.nextLine();
System.out.println(word(words));
}
}
You are over thinking it. Just loop through the array list once, whenever you see a longer word, store the word/or its index:
ArrayList <String> words= new ArrayList <String>();
String currLongest = words.get(0);
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
If your words are being passed as a single String delimited by spaces, the procedure is the same. Just split them before looping:
String[] words = str.split(" ");
String currLongest = words.[0];
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
Note that there is no need to store the longest word into a list because at any point of time, there should only be one longest word.
It'll be easier to chop up the string using split first. then you can simplify your codes to the following.
I have commented as much as I can in the code below
public static List<String> word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
ArrayList <String> longestWord= new ArrayList <String>(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.clear(); //remove the old entries
longestWord.add(theWord); // add the new word in
longestWordLength = theWord.length(); update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.add(theWord); // add the new word in
}
}
return longestWord;
}
it returns a list instead of a String for the event when several words are the same length.
edit alternatively you can use a StringBuilder too.
public static String word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
StringBuilder longestWord= new StringBuilder(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.setLength(0); //remove the old entries
longestWord.append(theWord); // add the new word in
longestWordLength = theWord.length(); //update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.append(" "); //add a spacing between each word (or any delimiter that you like)
longestWord.add(theWord); // add the new word in
}
}
return longestWord.toString();
}

Need help printing words in reverse in JAVA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am having troubles in JAVA. I am trying to get the string to print out backwards for each word.
Example: Hello World would be "olleh dlrow"
Below is my class. thanks for the help.
public class ReadReverse {
String message = "Hello nice to meet you in CS102";
String[] myStrings = message.split(" "); //Makes an array of the words split up by spaces
String result = "";
{
// gets the length of the array and splits it up by each word
for (int i = 0; i < myStrings[i].length(); i++) {
message.push(myStrings[i].at(i));
// sets th length to the length of the word
int length = message.length();
// pops the letter out into the new stack
for (i = 0; i < length; i++) {
result += myStrings;
}
// checks to see if it is at the end of the string.
if (i != message.length() - 1) {
result += " ";
}
}
}
}
You can achieve string reversal in many ways.
Have a look into this :
class ReverseString
{
public static void main(String[] args)
{
String input = "Hello world";
String[] words = input.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(input);
System.out.println(reversedString);
}
}
I would revert word by word in this way:
String input = "Hello world";
String[] words = input.split(" ");
StringBuilder reversed = new StringBuilder(
for (String word : words) {
reversed.append(new StringBuilder(word).reverse())
.append(" ");
}
System.out.println(reversed);
Or using java 8 streams this way :
String input = "Hello world";
StringBuilder reversed = new StringBuilder();
Stream.of(input.split(" "))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.forEach(word -> reversed.append(word).append(" "));
System.out.println(reversed);
Outputs : olleH dlrow

Categories