How do I get my output to contain the spaces I need? - java

I have to capitalize the first letter in every word passed into the string. My output is doing that capitalization, but it's not maintaining the format of the original output. For example, string input is "hello world", my output is "HelloWorld", and my desired output should be "Hello World."
I've tried to add spaces where I can throughout the code but nothing works. I think the problem is that when I use toCharArray, it gives me an output with no spaces? So my concatenation result is adding everything in one swoop, versus each word separately?
Or I thought that my code was using string concatenation with my result, and it's not being separated because I have both words going into the same variable.
import java.util.*;
import java.io.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for(int j = 0; j < charWord.length; j++ ) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result += (j == 0 ? cap : word[i].charAt(j));
}
}
return result;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
No errors. Just not getting desired output.

When you did String[] word = str.split(" ");, the space between each word is taken out and you are now left with only the words in an array. You should use String.join(" ", word) on the resultant words array to reverse the effects so you get the spaces back.
Instead of going through each word char by char, try this:
for(int i = 0; i < word.length; i++) {
word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);

Try this:
import java.util.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
}
return result;
}
private static String capitalize(String s){
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}

You can use the below code.
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for (int j = 0; j < charWord.length; j++) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result.append(j == 0 ? cap : word[i].charAt(j));
}
result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}

Related

Reverse each word of a string without altering their position(Without using inbuilt fucntion)

I want to reverse each individual word of a String in Java in different different sitautions (not the entire string, just each individual word).
Example1: if input String is "This is a test" then the output should be "sihT si a tset".
Example2: if input String is "This is a test" then the output should be "sihT si a tset".
[When there is more than one space between some words]
Please also provide algorithm for understanding
What I have tried so far
class reverseAString
{
public static void main(String args[])
{
String str= "Test the product";
String strArr[]= str.split(" ");
for(int i=0;i<=strArr.length-1;i++)
{
for(int j=strArr[i].length()-1; j>=0;j--)
{
System.out.print(strArr[i].charAt(j));
}
System.out.printf(" ");
}
}
}
---------
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}
This approach is much more succinct.
class StringRev{
public static void main(String args[]){
String str[] = "Test the product".split(" ");
String finalStr="";
for(int i = str.length-1; i>= 0 ;i--){
finalStr += str[i]+" ";
}
System.out.println(finalStr);
}
}
public static void main(String arg[]) {
System.out.println(reverseWords("This is a test"));
}
// function to reverse each word
public static String reverseWords(String input) {
String result = null;
StringBuffer strBuffer = new StringBuffer();
String split[] = input.split(" ");
for (String temp : split) {
if (temp != " ") {
strBuffer.append(reverse(temp));
strBuffer.append(" ");
} else {
strBuffer.append(" ");
}
}
result = strBuffer.toString();
return result;
}
// function to reverse individual word
public static String reverse(String input) {
StringBuffer strBuffer = new StringBuffer();
char[] charArray = input.toCharArray();
for (int j = charArray.length - 1; j >= 0; j--) {
strBuffer.append(charArray[j]);
}
return strBuffer.toString();
}
Split complete string on basis of space
Then convert each string to character array and reverse
individual word.
It's been a long time since I've touch Java, but here's the algorithm.
String stringToReverse = "This is a Test";
String finalString = "";
Stack word = new Stack;
for(int i = 0; i < stringToReverse.length; i++){
char chr = stringToReverse[i];
if(chr == " " || i == (stringToReverse.length - 1)){
while(word.count > 0){
finalString += word.pop();
}
finalString += chr;
}else{
word.push(chr);
}
}

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Remove repeated characters in a string

I need to write a static method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a String, it returns "make".
I already tried the following code, but it doesn't seem to display the last character.
Here's my code:
import java.util.Scanner;
public class undouble {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("enter String: ");
String str = console.nextLine();
System.out.println(removeSpaces(str));
}
public static String removeSpaces(String str){
String ourString="";
int j = 0;
for (int i=0; i<str.length()-1 ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
return ourString;
}
}
You could use regular expressions for that.
For instance:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));
Output:
done
Pattern explanation:
"(.)\\1{1,}" means any character (added to group 1) followed by itself at least once
"$1" references contents of group 1
maybe:
for (int i=1; i<str.length() ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:
EDIT:
public void removeSpaces(String str){
String ourString="";
for (int i=0; i<str.length()-1 ; i++){
if(i==0){
ourString = ""+str.charAt(i);
}else{
if(str.charAt(i-1) != str.charAt(i)){
ourString = ourString +str.charAt(i);
}
}
}
System.out.println(ourString);
}
if you cannot use replace or replaceAll, here is an alternative. O(2n), O(N) for stockage and O(N) for creating the string. It removes all repeated chars in the string put them in a stringbuilder.
input : abcdef , output : abcdef
input : aabbcdeef, output : cdf
private static String remove_repeated_char(String str)
{
StringBuilder result = new StringBuilder();
HashMap<Character, Integer> items = new HashMap<>();
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == null)
items.put(current, 1);
else
items.put(current, ocurrence + 1);
}
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == 1)
result.append(current);
}
return result.toString();
}
import java.util.*;
public class string2 {
public static void main(String[] args) {
//removes repeat character from array
Scanner sc=new Scanner(System.in);
StringBuffer sf=new StringBuffer();
System.out.println("enter a string");
sf.append(sc.nextLine());
System.out.println("string="+sf);
int i=0;
while( i<sf.length())
{
int j=1+i;
while(j<sf.length())
{
if(sf.charAt(i)==sf.charAt(j))
{
sf.deleteCharAt(j);
}
else
{
j=j+1;
}
}
i=i+1;
}
System.out.println("string="+sf);
}
}
Input AABBBccDDD, Output BD
Input ABBCDDA, Outout C
private String reducedString(String s){
char[] arr = s.toCharArray();
String newString = "";
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put(arr[0],1);
for(int index=1;index<s.length();index++)
{
Character key = arr[index];
int value;
if(map.get(key) ==null)
{
value =0;
}
else
{
value = map.get(key);
}
value = value+1;
map.put(key,value);
}
Set<Character> keyset = map.keySet();
for(Character c: keyset)
{
int value = map.get(c);
if(value%2 !=0)
{
newString+=c;
}
}
newString = newString.equals("")?"Empty String":newString;
return newString;
}
public class RemoveDuplicateCharecterInString {
static String input = new String("abbbbbbbbbbbbbbbbccccd");
static String output = "";
public static void main(String[] args)
{
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
char temp = input.charAt(i);
boolean check = false;
for (int j = 0; j < output.length(); j++) {
if (output.charAt(j) == input.charAt(i)) {
check = true;
}
}
if (!check) {
output = output + input.charAt(i);
}
}
System.out.println(" " + output);
}
}
Answer : abcd
public class RepeatedChar {
public static void main(String[] args) {
String rS = "maaaakkee";
String outCome= rS.charAt(0)+"";
int count =0;
char [] cA =rS.toCharArray();
for(int i =0; i+1<cA.length; ++i) {
if(rS.charAt(i) != rS.charAt(i+1)) {
outCome += rS.charAt(i+1);
}
}
System.out.println(outCome);
}
}
TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS:
package replace;
public class removingrepeatedcharacters
{
public static void main(String...args){
int i,j=0,count=0;
String str="noordeen";
String str2="noordeen";
char[] ch=str.toCharArray();
for(i=0;i<=5;i++)
{
count=0;
for(j=0;j<str2.length();j++)
{
if(ch[i]==str2.charAt(j))
{
count++;
System.out.println("at the index "+j +"position "+ch[i]+ "+ count is"+count);
if(count>=2){
str=str2;
str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
}
System.out.println("after replacing " +str2);
}
}
}
}
}
String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
outstr = outstr + str.charAt(i);
}
outstring = outstr + str.charAt(i);
}
System.out.println(outstring);
public static void remove_duplicates(String str){
String outstr="";
String outstring="";
for(int i=0;i<str.length()-1;i++) {
if(str.charAt(i)!=str.charAt(i+1)) {
outstr=outstr+str.charAt(i);
}
outstring=outstr+str.charAt(i);
}
System.out.println(outstring);
}
More fun with java 7:
System.out.println("11223344445555".replaceAll("(?<nums>.+)\\k<nums>+","${nums}"));
No more cryptic numbers in regexes.
public static String removeDuplicates(String str) {
String str2 = "" + str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i) && i != 0) {
continue;
}
str2 = str2 + str.charAt(i);
}
return str2;
}

How to reverse words of a Java String

Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}

Reverse a given sentence in Java

Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
"This is an interview question"
The output must be:
"question interview an is this"
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)
Just being different: a recursive solution. Doesn't add any extra spaces.
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
I will also improve on the split solution by using \b instead (it's so obvious!).
String[] parts = "Word boundary is better than space".split("\\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.
(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).
Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
a every boring bit of java:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
in groovy it's a little bit more readable:
"this is an interview question"
.split("\\s")
.reverse()
.join(' ')
I also give it a try: Here's a version using a stack and a scanner:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
I don't think you should use any library..
1) Reverse whole string
2) Reverse each word.
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
please try below solution, this is working for me.
public class reverseline {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="This is interview question";
String words[]=str.split(" ");
for(int i=words.length-1;i>=0;i--){
System.out.print(words[i]+" ");
}
}
}
Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());
Shortest Answer
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
List<String> reverseWord = Arrays.asList(words);
Collections.reverse(reverseWord);
Iterator itr = reverseWord.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
OR
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
for (int i = words.length-1 ; i >= 0; i--) {
System.out.print(words[i] +" ");
}
}
}

Categories