Reverse every 2nd word of a sentence - java

I am trying to reverse every 2nd words of every single sentence like
If a given string is :
My name is xyz
The desired output should be :
My eman is zyx
My current output is:
Ym eman s1 zyx
I am not able to achieve my desired output.Don't know what I am doing wrong here
Here is my code
char[] sentence = " Hi my name is person!".toCharArray();
System.out.println(ReverseSentence(sentence));
}
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin){
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}

If you want to reverse the alternate word you can try something like splitting the whole String into words delimited by whitespaces and apply StringBuilder reverse() on every second word like :-
String s = "My name is xyz";
String[] wordsArr = s.split(" "); // broke string into array delimited by " " whitespace
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i< wordsArr.length; i++){ // loop over array length
if(i%2 == 0) // if 1st word, 3rd word, 5th word..and so on words
sb.append(wordsArr[i]); // add the word as it is
else sb.append(new StringBuilder(wordsArr[i]).reverse()); // else use StringBuilder revrese() to reverse it
sb.append(" ");// add a whitespace in between words
}
System.out.println(sb.toString().trim()); //remove extra whitespace from the end and convert StringBuilder to String
Output :- My eman is zyx

You can solve your problem vary easy way! Just use a flag variable which will indicate the even or odd position, more precisely whether any word will gonna be reversed or not!
Look at the following modification I made in your code, just added three extra line:
private static boolean flag = true;// added a variable flag to check if we reverse the word or not.
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
flag = !flag; // first time (odd position) we are not going to reverse!
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin & flag){ //lets see whether we are going to reverse or not
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
Input
My name is xyz
Output:
My eman is zyx

The following code does this "special reverse" which reverses any other word in the sentence:
public static void main(String[] args) {
String sentence = "My name is xyz";
System.out.println(specialReverse(sentence)); // My eman is zyx
}
private static String specialReverse(String sentence) {
String result = "";
String[] words = sentence.split(" ");
// we'll reverse only every second word according to even/odd index
for (int i = 0; i < words.length; i++) {
if (i % 2 == 1) {
result += " " + reverse(words[i]);
} else {
result += " " + words[i];
}
}
return result;
}
// easiest way to reverse a string in Java in a "one-liner"
private static String reverse(String word) {
return new StringBuilder(word).reverse().toString();
}

Just for completeness here's Java-8 solution:
public static String reverseSentence(String input) {
String[] words = input.split(" ");
return IntStream.range(0, words.length)
.mapToObj( i -> i % 2 == 0 ? words[i] :
new StringBuilder(words[i]).reverse().toString())
.collect(Collectors.joining(" "));
}
reverseSentence("My name is xyz"); // -> My eman is zyx

package com.eg.str;
// Without using StringBuilder
// INPUT: "Java is very cool prog lang"
// OUTPUT: Java si very looc prog gnal
public class StrRev {
public void reverse(String str) {
String[] tokens = str.split(" ");
String result = "";
String k = "";
for(int i=0; i<tokens.length; i++) {
if(i%2 == 0)
System.out.print(" " + tokens[i] + " ");
else
result = tokens[i];
for (int j = result.length()-1; j >= 0; j--) {
k = "" + result.charAt(j);
System.out.print(k);
}
result = "";
}
}
public static void main(String[] args) {
StrRev obj = new StrRev();
obj.reverse("Java is very cool prog lang");
}
}

//reverse second word of sentence in java
public class ReverseSecondWord {
public static void main(String[] args) {
String s="hello how are you?";
String str[]=s.split(" ");
String rev="";
for(int i=0;i<str[1].length();i++)
{
char ch=str[1].charAt(i);
rev=ch+rev;
}
str[1]=rev;
for(int i=0;i<str.length;i++)
{
System.out.print(str[i]+" ");
}
}
}

Related

Java Programming: Replace all but first and last letters of each word with "_"

The purpose of this method is replace all but the first and last letters of each word with "_". I'm a complete novice when it comes to coding, so I'm certain my code is fairly incorrect. I think where my code starts functioning improperly is with the while loop.
EDIT: How do I make this method without using arrays or extra methods, like the split method?
public static String blankWords(String s1) {
StringBuilder sb = new StringBuilder();
if(s1.length() > 2) {
sb.append(s1.charAt(0));
for(int x = 1; x < s1.length() - 1; x = x + 1) {
char y = ' ';
while(y != s1.charAt(x)) {
sb.append("_");
x = x + 1;
}
}
sb.append(s1.charAt(s1.length() - 1));
return sb.toString();
}
return s1;
}
What my code is outputting:
HW2.blankWords("This is a Test.")
java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt(Unknown Source)
at HW2.blankWords(HW2.java:73)
What my code should output:
HW2.blankWords("This is a Test.")
"T__s is a T__t."
Here is a pretty simple solution:
class Scratch {
public static void main(String[] args) {
System.out.println(blankWords("My name is sam orozco"));
}
public static String delim = "_";
public static String blankWords(String s1) {
// this split arg on one or more space
String[] words = s1.split("\\s+");
StringBuilder response = new StringBuilder();
for (String val : words) {
val = convertWord(val);
response.append(val).append(" ");
}
return response.toString().trim();
}
public static String convertWord(String val) {
int len = val.length();
StringBuilder bldr = new StringBuilder();
int index = 0;
for (char ch : val.toCharArray()) {
if (index == 0 || index == len - 1) {
bldr.append(ch);
} else {
bldr.append(delim);
}
index++;
}
return bldr.toString();
}
}
You can do this using a StringTokenizer that will extract words based on a list of delimiters. Since you want to keep those delimiters in the output, you'll instruct the tokenizer to return them as tokens:
String blankWords(String s) {
// build a tokenizer for your string, listing all special chars as delimiters. The last argument says that delimiters are going to be returned as tokens themselves (so we can include them in the output string)
StringTokenizer tokenizer = new StringTokenizer(s, " .,;:?!()[]{}", true);
// a helper class to build the output string; think of it as just a more efficient concat utility
StringBuilder sb = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
String blankWord = blank(tokenizer.nextToken());
sb.append(blankWord);
}
return sb.toString();
}
/**
* Replaces all but the first and last characters in a string with '_'
*/
private String blank(String word) {
// strings of up to two chars will be returned as such
// delimiters will always fall into this category, as they are always single characters
if (word.length() <= 2) {
return word;
}
// no need to iterate through all chars, we'll just get the array
final char[] chars = word.toCharArray();
// fill the array of chars with '_', starting with position 1 (the second char) up to the last char (exclusive, i.e. last-but-one)
Arrays.fill(chars, 1, chars.length - 1, '_');
// build the resulting word based on the modified array of chars
return new String(chars);
}
Here is the contents of a test that validates this implementation, using TestNG:
#Test(dataProvider = "texts")
public void testBlankWords(String input, String expectedOutput) {
assertEquals(blankWords(input), expectedOutput);
}
#DataProvider
public Object[][] texts() {
return new Object[][] {
{"This is a test.", "T__s is a t__t."},
{"This one, again, is (yet another) test!", "T__s o_e, a___n, is (y_t a_____r) t__t!"}
};
}
The main drawback of this implementation is that StringTokenizer requires you to list all the delimiters by hand. With a more advanced implementation, you can consider a delimiter any character that returns false for Character.isAlphabetic(c) or however you decide to define your non-word chars.
P.S.
This could be a "more advanced implementation", as I mentioned above:
static String blankWords(String text) {
final char[] textChars = text.toCharArray();
int wordStart = -1; // keep track of the current word start position, -1 means no current word
for (int i = 0; i < textChars.length; i++) {
if (!Character.isAlphabetic(textChars[i])) {
if (wordStart >= 0) {
for (int j = wordStart + 1; j < i - 1; j++) {
textChars[j] = '_';
}
}
wordStart = -1; // reset the current word to none
} else if (wordStart == -1) {
wordStart = i; // alphabetic characters start a new word, when there's none started already
} else if (i == textChars.length - 1) { // if the last character is aplhabetic
for (int j = wordStart + 1; j < i; j++) {
textChars[j] = '_';
}
}
}
return new String(textChars);
}
No while loop necessary!
Look ahead by 1 character to see if it's a space, or if the current character is a space, in that case you append it. Otherwise you make sure to add the next character (skipNext false).
Always add the last character
public static String blankWords(String s1) {
StringBuilder sb = new StringBuilder();
if(s1.length() > 2) {
Boolean skipNext = false;
for(int x = 0; x < s1.length() - 1; x = x + 1) {
if(s1.charAt(x) == ' ' || s1.charAt(x + 1) == ' ') {
sb.append(s1.charAt(x));
skipNext = false;
}
else {
if(skipNext) {
sb.append('_');
}
else {
sb.append(s1.charAt(x));
skipNext = true;
}
}
}
sb.append(s1.charAt(s1.length() - 1));
return sb.toString();
}
return s1;
}
For the more advanced programmer, use regular expression.
public static String blankWords(String s1) {
return s1.replaceAll("\\B\\w\\B", "_");
}
This correctly keeps the final t, i.e. blankWords("This is a Test.") returns "T__s is a T__t.".

recursive function that checks if there are k words that they "charecter equale" to a given word

we will say that two words are "charecter equale" if both of them has the same charecter, for example: baac and abac are charecter equale, I am trying to write a recursive function that gets a string s, a word w and integer k, that checks if there are exactliy k words in the string that they charecter equale to the word, for example: the function should return true for the word abac , the string aabc abdca caba xyz ab and the number k=2.
Ineed help at the recursive part, i.e the function searchMixed, my idea was first the check if the string contain only on word (base case),
the general case is to call the function searchMixed without the first word
public class recursion1 {
public static void main(String[] args) {
boolean result=searchMixed("abac","aabc abdca caba xyz ab",2);
System.out.println("result: "+result);
}
public static boolean searchMixed(String word, String s, int k)
{
if(s.indexOf(' ')==-1 && isEquale(word,s) && k==1)
return true;
if(s.indexOf(' ')==-1 && !isEquale(word,s) && k==1)
return false;
int pos=s.indexOf(' ');
System.out.println("index of"+ s.indexOf(' '));
String first_word=first_word=s.substring(0,pos);
if(isEquale(word, first_word))
searchMixed(word, s.substring(pos+1), k-1);
else
searchMixed(word, s.substring(pos+1), k);
return false;
}
.
//this function works fine, the function checks if two words are charecter equale
public static boolean isEquale(String word, String sub_string)
{
if(word.length()!=sub_string.length())
return false;
char[] s33=new char[sub_string.length()];
char[] sww=new char[word.length()];
for(int i=0;i<sub_string.length();i++)
s33[i]=sub_string.charAt(i);
for(int i=0;i<word.length();i++)
sww[i]=word.charAt(i);
for(int i=0;i<word.length();i++)
{
for(int j=0;j<sub_string.length();j++)
{
if(sww[i]==s33[j])
s33[j]='#';
}
}
for(int i=0;i<sub_string.length();i++)
if(s33[i]!='#')
return false;
return true;
}
}
YourString = YourString.replaceAll("\\s+", " ");
String[] words = YourString.split(" ");
... to split the words.
static int n = 0;
static String keyword = "aabc";
static String[] words = null;
public static void main()
{
n = 0;
// Let's assume you accept 'k' here.
String YourString = "aabc baca hjfg gabac";
words = YourString.split(" ");
rec(words[0]);
if (k <= n)
System.out.println(true);
else
System.out.println(false);
}
static int pos = 0;
public static void rec(String word)
{
boolean flag = true;
word += " ";
if(word.length() != keyword.length() + 1)
{
flag = false;
}
for(int i = 0; i < keyword.length() && flag; i++)
{
for(int j = 0; j < word.length(); j++)
{
if(word.charAt(j) == keyword.charAt(i))
{
word = word.substring(0, j) + word.substring(j+1);
break;
}
}
if(word.equals(" "))
{
n++;
break;
}
}
if(pos + 1 != words.length)
{
rec(words[++pos]);
}
}
Now, let me explain:
In the recursive method rec(String word), a space is added to it at the end of the word being checked (so that substring(j+1) does not go out of bounds)
If the keyword and the checked word are of different lengths, it stops checking, and moves on to '5'.
If the two words are of same lengths, the loop removes a single similar character from the word (That's what word = word.substring(0, j) + word.substring(j+1); does).
At the end of the loop, if all that is remaining of the word is a space, then the counter n increases by 1 and the loop exits.
If there is more than or equal to one more Strings in the array, position of the word being checked in the array increases by 1, and the next word in the array is passed to the rec(String word) method.

pig latin-like program - issues with vowels

I'm writing a program that has two rules:
1. If the first character of the word is a vowel, then move it to the end of the word.
2. If the first character of the word is a consonant, then move it to the end of the word and append 'ae'.
import java.util.Scanner;
public class Program5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String english = scanner.nextLine();
String piggy = piggyEnglish(english);
System.out.print("Translated: " + piggy);
}
private static String piggyEnglish(String s) {
String piggy = "";
int i = 0;
while (i<s.length()) {
while (i<s.length() && !isLetter(s.charAt(i))) {
piggy = piggy + s.charAt(i);
i++;
}
if (i>=s.length()) break;
int begin = i;
while (i<s.length() && isLetter(s.charAt(i))) {
i++;
}
int end = i;
piggy = piggy + piggyWord(s.substring(begin, end));
}
return piggy;
}
private static boolean beginsWithVowel(String word){
String vowels = "aeiou";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}
private static boolean isLetter(char c) {
return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
}
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split) + word.substring(0, split);
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return i;
return 0;
}
}
The following is the expected output:
Please enter a sentence: today is a beautiful day
Translated: odaytae si a eautifulbae aydae
However, this is what I'm getting:
Please enter a sentence: today is a beautiful day
Translated: odaytae is a eautifulbae aydae
Basically, it doesn't translate any words that start with a vowel. I think the problem stems from the piggyWord method, but I'm not certain. Can I get any pointers on how to fix this?
The error lies in the piggyWord function:
private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split + 1) + word.substring(0, split + 1); //Since vowel is in 1st place, substring(0,0) returns empty string.
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}
Based on your rules, you don't need the method firstVowel() to get the index of the first vow in a word because you only need to know whether the first character in the word is a vow or not.
So simply change you piggyWord method to the following will solve your problem:
private static String piggyWord(String word) {
if(beginsWithVowel(word)) {
return word.substring(1) + word.substring(0, 1);
} else {
return word.substring(1) + word.substring(0, 1)+"ae";
}
}
Or more simply:
private static String piggyWord(String word) {
String result = word.substring(1) + word.substring(0, 1);
return beginsWithVowel(word) ? result : result + "ae";
}
Because you always have to move the first character of a word to the end, the only thing is that whether you need to append an extra "ae" in the end or not.
If only the first letter is concerned than in "firstVowel" you can return 1 if vowel is at first position.
private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return 1;
return 0;
}

implement basic string compression

I am working on question 1.5 from the book Cracking The Coding interview. The problem is to take a string "aabcccccaaa" and turn it into a2b1c5a3.
If the compressed string is not smaller than the original string, then return the original string.
My code is below. I used an ArrayList because I would not know how long the compressed string would be.
My output is [a, 2, b, 1, c, 5], aabc, []. When the program gets to the end of string, it doesn't have a character to compare the last character too.
import java.util.*;
import java.io.*;
public class stringCompression {
public static void main(String[] args) {
String a = "aabcccccaaa";
String b = "aabc";
String v = "aaaa";
check(a);
System.out.println("");
check(b);
System.out.println("");
check(v);
}
public static void check(String g){
ArrayList<Character> c = new ArrayList<Character>();
int count = 1;
int i = 0;
int h = g.length();
for(int j = i + 1; j < g.length(); j++)
{
if(g.charAt(i) == g.charAt(j)){
count++;
}
else {
c.add(g.charAt(i));
c.add((char)( '0' + count));
i = j;
count = 1;
}
}
if(c.size() == g.length()){
System.out.print(g);
}
else{
System.out.print(c);
}
}
}
In the last loop you're not adding the result to the array. When j = g.length() still needs to add the current char and count to the array. So you could check the next value of j before increment it:
for(int j = i + 1; j < g.length(); j++)
{
if(g.charAt(i) == g.charAt(j)){
count++;
}
else {
c.add(g.charAt(i));
c.add((char)( '0' + count));
i = j;
count = 1;
}
if((j + 1) = g.length()){
c.add(g.charAt(i));
c.add((char)( '0' + count));
}
}
I would use a StringBuilder rather than an ArrayList to build your compressed String. When you start compressing, the first character should already be added to the result. The count of the character will be added once you've encountered a different character. When you've reached the end of the String you should just be appending the remaining count to the result for the last letter.
public static void main(String[] args) throws Exception {
String[] data = new String[] {
"aabcccccaaa",
"aabc",
"aaaa"
};
for (String d : data) {
System.out.println(compress(d));
}
}
public static String compress(String str) {
StringBuilder compressed = new StringBuilder();
// Add first character to compressed result
char currentChar = str.charAt(0);
compressed.append(currentChar);
// Always have a count of 1
int count = 1;
for (int i = 1; i < str.length(); i++) {
char nextChar = str.charAt(i);
if (currentChar == nextChar) {
count++;
} else {
// Append the count of the current character
compressed.append(count);
// Set the current character and count
currentChar = nextChar;
count = 1;
// Append the new current character
compressed.append(currentChar);
}
}
// Append the count of the last character
compressed.append(count);
// If the compressed string is not smaller than the original string, then return the original string
return (compressed.length() < str.length() ? compressed.toString() : str);
}
Results:
a2b1c5a3
aabc
a4
You have two errors:
one that Typo just mentioned, because your last character was not added;
and another one, if the original string is shorter like "abc" with only three chars: "a1b1c1" has six chars (the task is "If the compressed string is not smaller than the original string, then return the original string.")
You have to change your if statement, ask for >= instead of ==
if(c.size() >= g.length()){
System.out.print(g);
} else {
System.out.print(c);
}
Use StringBuilder and then iterate on the input string.
private static string CompressString(string inputString)
{
var count = 1;
var compressedSb = new StringBuilder();
for (var i = 0; i < inputString.Length; i++)
{
// Check if we are at the end
if(i == inputString.Length - 1)
{
compressedSb.Append(inputString[i] + count.ToString());
break;
}
if (inputString[i] == inputString[i + 1])
count++;
else
{
compressedSb.Append(inputString[i] + count.ToString());
count = 1;
}
}
var compressedString = compressedSb.ToString();
return compressedString.Length > inputString.Length ? inputString : compressedString;
}

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

Categories