Determining the highest word alphabetically without arrays in java - java

I have been trying to write a program that does 2 things, finds the longest word in a user generated string and finding the highest word in alphabetical order. I have the longest word working fine, but I cant figure out the alphabetical problem to save my life. the problem I'm running into is how it is comparing the words running in the for loops. Any help would be appreciated!
/*
CSC 190
Hw7
Ryan Burchfield
10/19/17
Purpose: Take a string and return both the Longest and largest words in the String.
*/
package hw7;
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
String getLargest(String s1){
s1= s1 + " ";
String temp="", curWord="",largestW="";
char ltr;
for(int i=0; i<s1.length(); i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp= temp + ltr;
}else{
char ltr1;
for(int j=0; j<s1.length(); j++){
ltr1 = s1.charAt(j);
if(ltr1!=' ' && ltr1!=',' && ltr1!='.'){
curWord= curWord + ltr1;
}
else{
int largest = temp.compareToIgnoreCase(curWord);
System.out.println(temp+","+curWord+","+temp.compareToIgnoreCase(curWord));
System.out.println(largest);
if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
curWord="";
temp="";
}
}
}
}
return largestW;
}
}
public class Hw7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest word is: " + s1.getLargest(s));
}
}

if(largest > 0){
largestW=curWord;
}else{
largestW=temp;
}
This is where the program goes wrong. You did not compare currWord / temp with largestW
A better way to write getLargest() is to use the same way as getLongest(), i.e. using one loop, and compare largestW with temp every time (if largestW is empty then just set largestW = temp)

I would solve this with a single method that takes a Comparator<String> and the input String; construct a Scanner using the Scanner(String) constructor and modify the delimiter using Scanner#useDelimiter(String) to consume white space, commas, and literal '.'. Then use the supplied Comparator to compare the tokens available through the Scanner. Like,
static String findWord(Comparator<String> comp, String s1) {
Scanner sc = new Scanner(s1);
sc.useDelimiter("[\\s,\\.]+");
String max = null;
while (sc.hasNext()) {
String token = sc.next();
if (max == null || comp.compare(max, token) < 0) {
max = token;
}
}
return max;
}
Then, assuming you're using Java 8+, main can be written using Comparators already available like -
Comparator<String> stringLengthComparator = Comparator.comparingInt(
String::length);
Comparator<String> stringAlphaComparator = Comparator.naturalOrder();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String sentence = in.nextLine();
System.out.printf("Longest: %s%n", findWord(stringLengthComparator, sentence));
System.out.printf("Lexically: %s%n", findWord(stringAlphaComparator, sentence));
But, if you're using an earlier version - or you want to better understand what it does, the exact same code will work if you replace the two Comparators with equivalent code - like
Comparator<String> stringLengthComparator = new Comparator<String>() {
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
};
Comparator<String> stringAlphaComparator = new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
};

There's a lot of code there, nearly all of which is unnecessary.
Try this:
String longest = Arrays.stream(s.split(" +")).sort(comparing(String::length).reversed()).findFirst().get();
String highest = Arrays.stream(s.split(" +")).sort().reduce((a,b) -> b).get();
Note: Read and understand the code well before you submit your assignment.
Disclaimer: Code may not compile or even work as it was thumbed in on my phone (but there's a reasonable chance it will work)

As your post you can get the longest word. I will show you how to get the highest letter in alphabetical order of the longest word.
There is a method call toCharArray() you can use this method to make letter array of given word.
Than you can use casting to get integer value of the given char value
Then you can compare that integer value to get the highest integer value
Once you have the highest integer value cast that int value to char to take the letter
Following links to more information
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
http://javaseeeedu.blogspot.com/2015/12/casting-part-1.html
I have change your code try it
import java.util.Scanner;
class MyString{
String s;
MyString( String s1 ){
s=s1;
}
void setString(String s1){
s=s1;
}
String getLongest(String s1){
s1 = s1 +" ";
int length = s1.length();
String temp="", longestw="";
char ltr;
int templ, longest=0;
for(int i=0; i<length;i++){
ltr = s1.charAt(i);
if(ltr!=' ' && ltr!=',' && ltr!='.'){
temp=temp+ltr;
}
else{
templ=temp.length();
if(templ>longest){
longest=templ;
longestw=temp;
}
temp="";
}
}
return longestw;
}
char getLargest(String s1){
int max = 0;
char []arr = s1.toCharArray();
int temp[] = new int[arr.length];
for(int i=0;i<arr.length;i++){
temp[i] = (int)arr[i];
if(i!=0){
if(temp[i-1] < temp[i]){
max = temp[i];
}else{
max = temp[i-1];
}
}
}
return (char)max;
}
}
class Demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of words: ");
String s = in.nextLine();
MyString s1 = new MyString(s);
System.out.println("The longest word is: " + s1.getLongest(s));
System.out.println("The largest letter is: " + s1.getLargest(s1.getLongest(s)));
}
}

Related

How to replace characters in a string in Java without using .replace?

The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. I have provided a proposed solution at the end of my code snippet below.
public static char getKeyCharacter(String userInput) {
char keyCharacter;
Scanner inputStream = new Scanner(System.in);
while(userInput.length() > 1)
{
System.out.println("Please enter a SINGLE character to use as key: ");
userInput = inputStream.nextLine();
}
keyCharacter = userInput.charAt(0);
return keyCharacter;
}
public static String getString(String userResponse) {
Scanner inputStream = new Scanner(System.in);
String theString;
while(userResponse.length() > 500) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
while(userResponse.length() < 4) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
theString = userResponse;
return theString;
}
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
maskedString = maskedString + theString.replace(keyCharacter, mask);
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
public static String removeCharacter(String theString, char keyCharacter) {
String modifiedString = " ";
final char replaceChar = ' ';
modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
System.out.println("String with " + keyCharacter + " removed:");
return modifiedString;
}
public static int countKey(String theString, char keyCharacter) {
int charCount = 0;
for (int c = 0; c < theString.length(); c++) {
if (theString.charAt(c) == keyCharacter) {
charCount++;
}
}
System.out.println("Occurences of " + keyCharacter + " in string:");
return charCount;
}
}
I believe the solution is will look something like this, but thus far I've been unsuccesful -
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
for (int k = 0; k < theString.length(); k++) {
if (theString.charAt(k) == keyCharacter) {
keyCharacter = mask;
}
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. Thank you for the assistance in advance!
I would use a StringBuilder and String#toCharArray() with a simple for-each loop. Like,
public static String maskCharacter(String theString, char keyCharacter){
StringBuilder sb = new StringBuilder();
for (char ch : theString.toCharArray()) {
if (ch == keyCharacter) {
sb.append('$'); // <-- mask keyCharacter(s).
} else {
sb.append(ch); // <-- it isn't the character to mask
}
}
return sb.toString();
}
I wouldn't use a StringBuilder: just use the result of toCharArray() directly:
char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);
Not only is it more concise, but:
It will run faster, because it's cheaper to access an array element than to invoke a method; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that);
It will use less memory, because it doesn't require storage for the copy inside StringBuilder.
public static String maskCharacter(String theString, char keyCharacter){
String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {
if (theString.charAt(i) == keyCharacter) {
masked += "$";
}
else {
masked+=theString.charAt(i)+"";
}
}
return masked;
}
An answer that only uses string concatenation and basic character access.
You seem to know that you can concatenate something to a string and get a different string.
maskedString = maskedString + ...;
You also know you can build a for-loop that gets each individual character using .charAt()
for (int k = 0; k < theString.length(); k++) {
char nch = theString.charAt(k);
}
You can check equality between chars
if (nch == keyCharacter)
... assuming you know about else-branches, isn't it clear you just need to put them together?
if (nch == keyCharacter) {
// append '$' to maskedString
}
else {
// append nch to maskedString
}
Of course this creates a new string on every loop iteration so it is not terribly efficient. But I don't think that's the point of the exercise.

Java Given 2 Strings write a method to decide if one is a permutation of the other

That is a question from Cracking the coding interview.Below is my code:
class PalinDrome {
public static Scanner userinput = new Scanner(System.in);
public static void main(String [] args){
//1st input from user
System.out.println("Enter 1st string: ");
String s1= userinput.next().toLowerCase();
// convert 1st string to char Array
char [] charS1= s1.toCharArray();
System.out.println(charS1);
//2nd input from user
System.out.println("Enter 2nd string: ");
String s2= userinput.next().toLowerCase();
// convert 2nd string to char Array
char [] charS2= s2.toCharArray();
System.out.println(charS2);
if(s1.length()==s2.length() && s1.toCharArray()==s2.toCharArray()){
System.out.println(" Word 2 is Perm of 1st word");
}
else{
System.out.println(" Word 2 is not Perm of 1st word");
}
}
}
Question: When I use Tom(1st) and 2nd Mot/moT (tried different variations), I always get Not perm of 1st word. There are answers in the book, I want to know whats wrong with this logic. Thank in advance.
As mentioned in the comment s1.toCharArray()==s2.toCharArray() is wrong because you are not really comparing values in the array just the references of those 2 newly created arrays.
You should sort those arrays Arrays.sort
And then use Arrays.equals to compare those arrays.
Here is a solution using wether collections nor sorting. ^^
Idea is to mark entries in both Strings/char arrays that are the same character until everything is marked. (after checking the strings for same length)
package PermuteString;
public class Permutation {
public static void main(String[] args) {
String a = "yalla";
String b = "allay";
String c = "allas";
Permutation permutation = new Permutation();
if (permutation.isPermutationWithoutCollection(a, b))
System.out.println(a + " is permutation of " + b);
if (!permutation.isPermutationWithoutCollection(a, c))
System.out.println(a + " is not a permutation of " + c);
}
public boolean isPermutationWithoutCollection(String string1, String string2) {
if (string1.length() != string2.length()) {
return false;
}
char[] a = string1.toLowerCase().toCharArray();
char[] b = string2.toLowerCase().toCharArray();
for (int i = 0; i < a.length; i++) {
boolean unChanged = true;
for (int k = 0; k < b.length; k++) {
if (a[i] == b[k]) {
a[i] = 'A';
b[k] = 'B';
unChanged = false;
break;
}
}
if (unChanged) {
//System.out.println("wawawa");
return false;
}
}
return true;
}
}
Yields:
yalla is permutation of allay
yalla is not a permutation of allas
Really depends on what topic the interview is based (based on using java / based on algorithm).

Find the longest word in a String

Following is my code:
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.replace(cut," ");
}
return lon;
}
The problem is that when I input a string like,
"a boy is playing in the park"
it returns the longest word as "ying" because when it replaces 'cut' with " " for the first time, it removes all the 'a'-s too, such that it becomes
" boy is pl ying in the p rk" after the first iteration of the loop
Please figure out what's wrong?
Thanks in advance!
You have already known the problem: the program does unwanted replacement.
Therefore, stop doing replacement.
In this program, the word examined is directly cut instead of using the harmful replacement.
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.substring(use+1); // cut the word instead of doing harmful replacement
}
return lon;
}
You can use the split function to get an array of strings.
Than cycle that array to find the longest string and return it.
String LongestWord(String a) {
String[] parts = a.split(" ");
String longest = null;
for (String part : parts) {
if (longest == null || longest.length() < part.length()) {
longest = part;
}
}
return longest;
}
I would use arrays:
String[] parts = a.split(" ");
Then you can loop over parts, for each element (is a string) you can check length:
parts[i].length()
and find longest one.
I would use a Scanner to do this
String s = "the boy is playing in the parl";
int length = 0;
String word = "";
Scanner scan = new Scanner(s);
while(scan.hasNext()){
String temp = scan.next();
int tempLength = temp.length();
if(tempLength > length){
length = tempLength;
word = temp;
}
}
}
You check the length of each word, if it's longer then all the previous you store that word into the String "word"
Another way uses Streams.
Optional<String> max = Arrays.stream("a boy is playing in the park"
.split(" "))
.max((a, b) -> a.length() - b.length());
System.out.println("max = " + max);
if you are looking for not trivial Solution ,you can solve it without using split or map but with only one loop
static String longestWorld(String pharagragh) {
int maxLength = 0;
String word=null,longestWorld = null;
int startIndexOfWord = 0, endIndexOfWord;
int wordLength = 0;
for (int i = 0; i < pharagragh.length(); i++) {
if (pharagragh.charAt(i) == ' ') {
endIndexOfWord = i;
wordLength = endIndexOfWord - startIndexOfWord;
word = pharagragh.substring(startIndexOfWord, endIndexOfWord);
startIndexOfWord = endIndexOfWord + 1;
if (wordLength > maxLength) {
maxLength = wordLength;
longestWorld = word;
}
}
}
return longestWorld;
}
now lets test it
System.out.println(longestWorld("Hello Stack Overflow Welcome to Challenge World"));// output is Challenge
Try :
package testlongestword;
/**
*
* #author XOR
*/
public class TestLongestWord{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(LongestWord("a boy is playing in the park"));
}
public static String LongestWord(String str){
String[] words = str.split(" ");
int index = 0;
for(int i = 0; i < words.length; ++i){
final String current = words[i];
if(current.length() > words[index].length()){
index = i;
}
}
return words[index];
}
}

write a code to find the number of words in a string using methods

I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT:
I have changed the code to
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
The getInputString method signature should be:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount method signature should be:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main method should look something like this:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
Use trim() and split() on 1-n whitespace chars:
private static int getWordCount(String s) {
return s.trim().split("\\s+").length;
}
The call to trim() is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
The parameter "\\s+" is necessary to count multiple spaces as a single word separator. \s is the regex for "whitespace". + is regex for "1 or more".
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
Happy learning!
You can do this by :
private static int getWordCount(String input) {
return input.split("\\s+").length;
}
Use String.split() method like :
String[] words = s.split("\\s+");
int wordCount = words.length;
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main() method that does this for you, for example:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
Based on your code i think this is what you're trying to do:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
I've moved the code you were 'playing' with into the right method (getWordCount).
Corrected the loop you were trying to use (I think you have for and while loops confused)
Fixed your check for the space character (' ' not " ")
There is a bug in this code which you'll need to work out how to fix:
getWordCount("How are you"); will return 2 when it should be 3
getWordCount(""); will return 0
getWordCount("Hello"); will return 0 when it should be 1
Good luck!
Better use simple function of spilt() with arguments as space
int n= str.split(" ").length;
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}

Reversing characters in each word in a sentence - Stack Implementation

This code is inside the main function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty() function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence I am getting this output: lpmaxe. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence ---> sihT si a ecnetnes
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String split function, iterate through the words, and reverse their orders.
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord is defined as:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty method has been changed to:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
Read each character from the input string and push that character to the stack
When the input string is empty, pop each character from the stack and print it to screen.
So:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence you want it to output elpmaxe ecnetnes not ecnetnes elpmaxe.
The reason that you see lpmaxe instead of elpmaxe is because your inner while-loop doesn't process the last character of the string since you have i < sentence.length() - 1 instead of i < sentence.length(). The reason that you only see a single word is because your sentence variable consists only of the first token of the input. This is what the method Scanner.next() does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine().
Hope this helps.
Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') { to something like if (c == ' ' || c == '.' || c == ',') { and so on.)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
public class ReverseofeachWordinaSentance {
/**
* #param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
This can pass in leetcode

Categories

Resources