icantcode
icantcode

Reputation: 167

Reversing a string word by word without use of built in function

I have written a program which is not working to revere the string word by word.

Input:

This is a boy

Expected output:

boy a is This

Output received:

boy a boy is a boy

Can you help me complete/correct the code?

public class Title {
    public static void main(String args[]) {
        String rev = "This is a boy";
        char a[] = new char[rev.length()];
        int i, j;
        for (i = a.length - 1; i >= 0; i--) {
            a[i] = rev.charAt(i);
            if (a[i] == ' ' || i == ' ') {
                for (j = i + 1; j < a.length; j++) {
                    a[j] = rev.charAt(j);
                }
                String n = new String(a);
                System.out.print(n);
            }
        }
    }
}

Upvotes: 0

Views: 949

Answers (4)

Mage Xy
Mage Xy

Reputation: 1803

Tested and confirmed working, and it does not use any String functions other than length() and charAt(int) (both of which you also used, so I assumed it was okay):

public static void main(String []args){
    String rev = "This is a boy";
    String currentWord = "";

    for (int i=rev.length()-1; i>=0; i--)
    {
        if (rev.charAt(i) == ' ')
        {
            printWordReversed(currentWord);
            currentWord = "";
        }
        else
            currentWord = currentWord + rev.charAt(i);
    }

    // Have to print out the last word
    printWordReversed(currentWord);
    System.out.println(); // new line for formatting
 }

 public static void printWordReversed(String word)
 {
     for(int i=word.length()-1; i>=0; i--)
     {
         System.out.print(word.charAt(i));
     }
     System.out.print(" ");
 }

Java fiddle

The way this works is by storing the current "word" in a string as you loop through each character in the string. As soon as you hit a whitespace, print and clear the current word. However, since we're iterating through the string backwards, the word we extract is going to have the characters in reverse order, so we have to re-reverse them.

Upvotes: 3

Animesh Kumar Paul
Animesh Kumar Paul

Reputation: 2294

Here,

  1. method:

    Check there is any space, if there is any, then copy char to other array. And the last for the 1st word, use other section to copy it because there is no space at the 1st character:

    public class Title {
        public static void main(String args[]) {
            String rev = "This is a boy";
            char a[] = new char[rev.length()];
            int i, j;
            int index =0;
            int previous = a.length;
            for (i = a.length - 1; i >= 0; i--) {
                if (rev.charAt(i) == ' ' ) {
                    for (j = i + 1; j < previous; j++) {
                        a[index] = rev.charAt(j);
                        index ++;
                    }
                    a[index++] = ' ';
                    previous = i;
                }
            }
            for (j = 0; j < previous; j++) {
                a[index] = rev.charAt(j);
                index ++;
            }
            String n = new String(a);
            System.out.print(n);
        }
    }
    
  2. method:

    First split the string and then print it in a reverse order:

    public class Title {
        public static void main(String args[]) {
            String rev = "This is a boy";
            String []a = rev.split(" ");
    
            for (int i = a.length - 1; i >= 0; i--) {
                if (i == a.length-1)
                    System.out.print(a[i]);
                else
                    System.out.print(" "+a[i]);
            }
        }
    }
    

Upvotes: 2

YoungHobbit
YoungHobbit

Reputation: 13402

Read the words from backwards and store them in separate String, as you encounter the whitespace. Add the whitespace separately once the word is added to the reverseString.

public class Title {
  public static void main(String args[]){
    String str = "This is a boy";
    String tmp = "";
    String reverString = "";
    for(int i =str.length()-1; i>=0; i--){
      tmp += i!=0 ? str.charAt(i) : str.charAt(i) + " ";  // store the words in tmp;
      if(str.charAt(i) == ' '|| i==0) {                   // once whitespace occure, store in reverseString
        for(int j=tmp.length()-2; j>=0; j--){            // start with length()-2, because last char is whitespace.
          reverString += tmp.charAt(j);
        }
        if (i != 0)
          reverString = reverString + " ";              // add the whitespace after each word except last word (This)
        tmp = "";
      }
    }
    System.out.println(reverString);
  }
}

Upvotes: 2

libik
libik

Reputation: 23029

It is always good approach to separate functionality into lower-level functions and then use them. It is more readable, easier to test and fix.

In your case, this can be done for example

public static void main(String[] args) {
    String input = "This is a boy";
    List<String> separated = separateWords(input);
    for (int i = separated.size() - 1; i >= 0; i--) {
        System.out.print(separated.get(i));
        if (i != 0){
            System.out.print(" ");
        }
    }
}   

public static List<String> separateWords(String line) {
    List<String> list = new ArrayList<String>();
    String actualString = "";
    for (int i = 0; i < line.length(); i++) {
        if ((line.charAt(i) == ' ') || (i == line.length() - 1)) {
            if (i == line.length() - 1){
                actualString += line.charAt(i);
            }
            list.add(actualString);
            actualString = "";
        } else {
            actualString += line.charAt(i);
        }
    }
    return list;
}

Also if you insist on "your" solution, the most important thing you are missing is "end". In my case, it is variable "max". It remembers the end of word you want to copy.

public static void main(String[] args) {
    String rev = "This is a boy";
    String out = "";

    int skipSpace = 1;
    int max = rev.length();
    for (int i = rev.length() - 1; i >= 0; i--) {
        if (rev.charAt(i) == ' ' || i == 0) {                
            if (i==0){
                skipSpace = 0;
            }
            for (int j = i + skipSpace; j < max; j++) {
                out += rev.charAt(j);
            }
            if (i != 0) {
                out += " ";
            }
            max = i;
        }
    }
    System.out.println(out);
}

Upvotes: 3

Related Questions