Mission Coding
Mission Coding

Reputation: 311

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

Upvotes: 0

Views: 337

Answers (5)

Abdou Amari
Abdou Amari

Reputation: 66

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());

Upvotes: 2

Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

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

Upvotes: 1

Henry Zhu
Henry Zhu

Reputation: 2618

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

Upvotes: 3

1337joe
1337joe

Reputation: 2367

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.

Upvotes: 1

Andrew Malta
Andrew Malta

Reputation: 850

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.

Upvotes: 1

Related Questions