How to find the last word in a string - java

I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.
I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!

You can do this:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
and you've got your last word.
You are splitting the original string at every space and storing the substrings in an array using the String#split method.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).

String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
Output:
Wines

String#lastIndexOf and String#substring are your friends here.
chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);

You can use: (if you are not familiar with arrays or unusual methods)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}

you just need to traverse the input string from tail when first find blank char stop traverse work and return the word.a simple code like this:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}

You could try:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));

Related

How to write a Java program to include whitespaces at the beginning of a string that we want to reverse?

I want to reverse a string.
input: Computer;
This input contains 4 whitespaces in the beginning of the word 'computer'.I want to include these 4 whitespaces in the beginning of the reversed string also.So,the program should include all the whitespaces I put at the beginning while taking the reverse too(I put 4 whitespaces as an example only).
output:" retupmoc";
I am attaching my code here.
package BasicTesting;
import java.util.*;
public class Corrected_StringRev {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();
String reversed = reverseString( str );
System.out.println( reversed );
}
public static String reverseString( String newString ) {
char ch[]=newString.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
How can I change this code to include the above requirement.Please,rewrite the code.Hope ypu will help.Thanks in adavance!
The logic is simple:
Traverse the start of the string and add whitespaces to rev until you meet the first non-whitespace
Do your string reversal and stop before the whitespace section begins
public static String reverseString(String newString) {
char ch[] = newString.toCharArray();
String rev = "";
int nWhitespace;
for (nWhitespace = 0; nWhitespace < ch.length; nWhitespace++) {
if (!Character.isWhitespace(ch[i]) {
break;
}
rev += ch[i];
}
for(int i = ch.length - 1; i >= nWhitespace; i--){
rev += ch[i];
}
return rev;
}
By the way, you can improve your code by using StringBuilder instead of +=.
Here instead of keeping a count and then adding it, we will be checking if the character we are at currently in the string is a whitespace character. If yes, we add a space to our string builder.
As soon as we come across a non-whitespace character, we break out of the loop.
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
What this code does is:
Take string inputString and trim it (remove trailing and leading whitespaces.
Creates a new (anonymous) object of a StringBuilder and reverses it.
Convert it into a string to append it to our original StringBuilder strB after the whitespaces.
Finally, we convert it into String and return it.
Some tips:
I will be using StringBuilder as it is mutable so saves space and also it contains a function to reverse it directly.
You should not call the length function of string in the loop as it will call it for every loop. Better to store the value in a variable and use that variable in the loop.
public static String reverseString(String inputString) {
StringBuilder strB = new StringBuilder();
int len = inputString.length();
for (int i = 0; i<len && inputString.charAt(i) == ' '; i++) {
strB.append(" ");
}
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
}

Java - Make character after space uppercase?

I'm trying to have the letter after every space turn uppercase. Can someone tell me what's wrong with the following method? Given phrase "this is a test" it returns "ThIs Is A TesT" instead of "this Is A Test"
public String toTitleCase(String phrase) {
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
phrase = phrase.replace(phrase.substring(i+1,i+2),phrase.substring(i+1,i+2).toUpperCase());
}
}
return phrase;
}
The problem in your code is that String.replace replaces each target character present in the String, and not only the one you want.
You could work directly on an array of chars instead of on the String:
public static String toTitleCase(String phrase) {
// convert the string to an array
char[] phraseChars = phrase.toCharArray();
for (int i = 0; i < phraseChars.length - 1; i++) {
if(phraseChars[i] == ' ') {
phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
}
}
// convert the array to string
return String.valueOf(phraseChars);
}
It's replacing all t, try below code.
It will help you.
String phrase="this is a test";
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
System.out.println(phrase.substring(i+1,i+2));
phrase = phrase.replace(phrase.substring(i,i+2),phrase.substring(i,i+2).toUpperCase());
}
}
System.out.println(phrase);
Use streams (or split) to split your string into parts, don't do it manually using substring.
Try below code
String test = "this is a test";
UnaryOperator<String> capitalize = str ->
str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();
String result =
Stream.of(
test.split(" ")
).map(capitalize)
.collect(
Collectors.joining(" ")
);
System.out.println(result);
Output: This Is A Test
When you replace a substring it will replace the each occurrence of that substring - which is not necessarily the one you are trying to replace. This is why it is replacing letters inside words.
Switching to a StringBuilder here to poke individual characters. Note that we don't traverse the entire String because there is no next-character to capitalize at the last character.
public String toTitleCase(String phrase) {
StringBuilder sb = new StringBuilder(phrase);
for (int index = 0 ; index < phrase.length - 1 ; ++index) {
if (sb.charAt(index) == ' ') {
sb.setCharAt(index + 1, Character.toUppercase(sb.charAt(index + 1)));
}
}
return sb.toString();
}
If a letter is first in any word, it will be replaced everywhere. In your case, all t,i and a will be uppercase.
Taking example for is. It is find a space before. Than in if body, what actually happen:
phrase = phrase.replace("i","I");
And all i are replaced with I.
String class cannot replace at a specific position.
You have to options:
using StringBuilder which can replace at a specific position.
String toTitleCase(String phrase) {
StringBuilder sb= new StringBuilder(phrase);
for (int i=0; i<phrase.length(); i++) {
if(i==0 || phrase.charAt(i-1)==' ') {
sb.replace(i,i+1,phrase.substring(i,i+1).toUpperCase());
}
}
return sb.toString();
}
or with stream, which is the method I prefer because is one-line. This way you don't preserve white-spaces( multiple consecutive white-spaces will be replaced with only one space), but usually you want this.
Arrays.asList(phrase.split("\\s+")).stream().map(x->x.substring(0,1).toUpperCase()+x.substring(1)).collect(Collectors.joining(" "));

Remove letter ā€œeā€ in the end of each word Java

Need help. Remove letter ā€œeā€ in the end of each word if word length > 1.
I have tried to do it via strig split and toCharArray, but I can't convert array after removing to string.
Thank you in advance.
public class RemoveE {
public static void main(String args[]) {
String str = "like row lounge dude top";
String[] words = str.split("\\s|[,.;:]");
for (String subStr : words) {
if (subStr.endsWith("e"))
subStr = subStr.substring(0, subStr.length() - 1);
String finalString = new String(subStr);
System.out.println(finalString);
}
}
}
It would be much simpler if you do it via regex like this
finalString = str.replaceAll("e\\b", "");
This is giving following output:
lik row loung dud top
PS: This solution assumes that you would like to drop even a single e in string since in the question, we're using if (subStr.endsWith("e")) which will also remove a single e in the String.
For your code, all the splitting and if conditions are right, all you need to do is add the subStr to finalString when process is completed. I've re-arranged 3 lines from your code, you can find explanation within comments:
public class RemoveE {
public static void main(String args[]) {
String str = "like row lounge dude top";
String[] words = str.split("\\s|[,.;:]");
String finalString = ""; // Bring the declaration outside of for loop
for (String subStr : words) {
if (subStr.endsWith("e"))
subStr = subStr.substring(0, subStr.length() - 1);
finalString += subStr + " "; // Add the substring and a whitespace to substring and add it to finalString to create the sentence again
}
System.out.println(finalString); // Print the String outside of final `for` loop
}
}
This gives the following output:
lik row loung dud top
Raman's first answer provides a good start for a solution with a regular expression. However to ensure that that it only drops the e if the word itself has more than one character, you can add a negative lookbehind to ensure that there is no word boundary immediately before the letter e with (?<!\\b) :
String str = "like row lounge dude top e";
String replaced = str.replaceAll("(?<!\\b)e\\b", "");
System.out.println("Replaced: " + replaced);
This solution is without regex. Adding this as reference as this may be helpful too in future.
I guess, explanation is not needed as a new char array is created and simple for-loop is used to iterate through the input string and keep the valid char in the new char array in appropriate position by checking the conditions.
public class RemoveE {
public static void main (String[] args) {
String str = "like row lounge dude top";
char[] strChars = str.toCharArray();
int size = str.length();
int temp = 0;
char[] newStringChars = new char[size];
String newString = null;
newStringChars[0] = strChars[0];
for(int i=1; i<size; i++) {
if(!(strChars[i] == 'e' && strChars[i+1] == ' ')) {
temp++;
newStringChars[temp] = strChars[i];
}
else if(strChars[i] == 'e' && strChars[i+1] == ' ' && strChars[i-1] == ' ') {
temp++;
newStringChars[temp] = strChars[i];
}
else {
continue;
}
}
newString = String.valueOf(newStringChars);
System.out.println(newString);
}
}
For String str = "like row lounge dude top"; output is:
lik row loung dud top
AND
For String str = "like row e lounge dude top"; (only one e present
in a word, i.e. not word length > 1 as mentioned in the question),
output is:
lik row e loung dud top

Replace " " of a string with "%20" - Complexity issue, which of the two below mentioned should be preferred?

Converting it to char array and then concatenating it back replacing spaces with "%20".
OR
Dividing string into substrings with "white space" as the "separator" and just combining the strings with "%20" between them.
For eg:
Str = "This is John Shaw "
(There are as many extra spaces at the end as there are spaces in the string)
expected outcome:
"This%20is%20John%20Shaw"
Is it not this ?
txt = txt.replaceAll(" ", "%20");
Let me know if I understood it wrong.
By replaceAll method of the String class as follow.
String str = "This is John Shaw ";
str = str.replaceAll(" ", "%20");
Output
This%20is%20John%20Shaw%20
You can write both algorithms with a complexity O(n) where n is the number of characters in the String but there are much better algorithms to do that.
By the way I wrote an example that show you the computing time, one method is faster than the other but they are both, as I said, O(n)
public class ComplexityTester
{
//FIRST METHOD
public static String replaceSpacesArray(String str)
{
str = str.trim(); // leading and trailing whitespaces omitted
char[] charArray = str.toCharArray();
String result = "";
for(int i = 0; i<charArray.length; i++) // it replaces spaces with %20
{
if(charArray[i] == ' ') //it's a space, replace it!
result += "%20";
else //it's not a space, add it!
result += charArray[i];
}
return result;
}
//SECOND METHOD
public static String replaceSpacesWithSubstrings(String str)
{
str = str.trim(); // leading and trailing whitespaces omitted
String[] words = new String[5]; //array of strings, to add substrings
int wordsSize = 0; //strings in the array
//From the string to an array of substrings
//(the words separated by spaces of the string)
int indexFrom = 0;
int indexTo = 1;
while(indexTo<=str.length())
{
if(wordsSize == words.length) //if the array is full, resize it!
words = resize(words);
//we reach the end of the sting, add the last word to the array!
if(indexTo == str.length())
{
words[wordsSize++] = str.substring(indexFrom, indexTo++);
}
else if(str.substring(indexTo-1,indexTo).equals(" "))//it's a space
{
//we add the last word to the array
words[wordsSize++] = str.substring(indexFrom, indexTo-1);
indexFrom = indexTo; //update the indices
indexTo++;
}
else //it's a character not equal to space
{
indexTo++; //update the index
}
}
String result = "";
// From the array to the result string
for(int i = 0; i<wordsSize; i++)
{
result += words[i];
if(i+1!=wordsSize)
result += "%20";
}
return result;
}
private static String[] resize(String[] array)
{
int newLength = array.length*2;
String[] newArray = new String[newLength];
System.arraycopy(array,0,newArray,0,array.length);
return newArray;
}
public static void main(String[] args)
{
String example = "The Java Tutorials are practical guides "
+"for programmers who want to use the Java programming "
+"language to create applications. They include hundreds "
+"of complete, working examples, and dozens of lessons. "
+"Groups of related lessons are organized into \"trails\"";
String testString = "";
for(int i = 0; i<100; i++) //String 'testString' is string 'example' repeted 100 times
{
testString+=example;
}
long time = System.currentTimeMillis();
replaceSpacesArray(testString);
System.out.println("COMPUTING TIME (ARRAY METHOD) = "
+ (System.currentTimeMillis()-time));
time = System.currentTimeMillis();
replaceSpacesWithSubstrings(testString);
System.out.println("COMPUTING TIME (SUBSTRINGS METHOD) = "
+ (System.currentTimeMillis()-time));
}
}

Find longest word in a sentence recursively

So I need to find the longest word recursively, I've written the code, but it's not working, and I have no idea what to fix.
public static String longestWord(String sentence)
{
int i = sentence.indexOf(" ");
if (i==-1){
return sentence;
}
else{
String first = sentence.substring(0,i);
String rest = sentence.substring(i+1);
if(first.length()>=rest.length()){
return longestWord(first);
}
else{
return longestWord(rest);
}
}
}
The line:
if(first.length() >= rest.length())
should read like:
String res = longestWord(rest);
if(first.length() >= res.length())
The reason it does not work is that you are ignoring the length of the longestWord(rest): instead of comparing the length of the initial word and the rest of the sentence, you should compare the length of the initial word to the length of the longest word found in the rest of the sentence.
String first = sentence.substring(0,i);
String rest = longestWord(sentence.substring(i+1));
return first.length()>=rest.length() ? first : rest;
Your basic approach is sane: you're breaking the input into two: the first word, and the rest of the string. But then the logic is bungled a little bit.
If the first word is longer than the entire rest of the string, you should just return first, not longestWord(first) (although, you do handle that case: longestWord will notice that the word cannot be split and just return it. It's pointless though).
Secondly, if that is not the case, you cannot assume that the first word is not the longest word. You must capture the return value of longestWord(rest), and then compare that word's length to the length of first. If that word is longer, then return it. Otherwise return first.
The essence of "divide and conquer" by recursion is that you solve some smaller versions of the problem, and then integrate those results. Don't forget this second part. This is not a binary search tree search where the data is organized such that you can just recurse to one half of the space or the other to find the answer. You don't know where the longest word might be.
This is another approach to solve the question:
public static String longestWord(String sentence) {
return longest(sentence.split("\\s+"), 0, 0);
}
private static String longest(String[] words, int idx, int longest) {
if (idx == words.length)
return words[longest];
return longest(words, idx+1,
words[idx].length() > words[longest].length() ? idx : longest);
}
First, in longestWord() the sentence gets split by its spaces, producing an array of words. From that point on, the method longest() recursively iterates over all the words passing the index of the longest one found so far in the longest parameter, until there are no more words. This is an efficient answer, as it doesn't create substrings at each step.
package com.kota.java;
import java.util.*;
class LongestWord{
String str = "Ram is intelligent boy";
String stringArray[] = str.split("\\s");
public String compare(String st1, String st2) {
if (st1.length() > st2.length()) {
return st1;
} else {
return st2;
}
}
LongestWord() {
String word = "";
for (int i = 0; i < stringArray.length; i++) {
if (i == 0) {
word = stringArray[0];
}
word = compare(word, stringArray[i]);
}
System.out.println("Longest word = " + word);
}
public static void main(String[] args) {
new LongestWord();
}
}
/**
* Out put : Longest word = intelligent
*
* */

Categories