Thursday, February 9, 2017

Reversing each word of the string with blank space preserved in Python and Java

we can come in the situation that we need to reverse each word of the string and also we need to preserve the blank space i.e we may have more than one space character in between each word and that needs to be preserved as well. Here I have mentioned the code for Python and Java.

Input:   "   I         am Laxmi     Kadariya"
Output:     I         ma imxaL     ayiradaK 

Algorithm:
1) split the string in to words:
2) reverse each word
3) finally join all the reverse word with space
def rev_string(test):
 final_str = ''
 words = test.split(' ')
 for x in words:
  rev_word = x[::-1]
  final_str = final_str + rev_word + ' ' 

 print final_str


 
  



if __name__ == '__main__':
 test = "   I         am Laxmi     Kadariya"
 rev_string(test)

Java Code:

/**
 * Created by laxmikadariya on 2/8/17.
 */
public class string_rev {
    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");

        String reverseString = "";

        for (int i = 0; i < words.length; i++)
        {
            String word = words[i];


            String reverseWord = "";

            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }

            reverseString = reverseString + reverseWord + " ";
        }

        System.out.println(inputString);

        System.out.println(reverseString);

        System.out.println("-------------------------");
    }

    public static void main(String[] args)
    {
        reverseEachWordOfString("   I am     Laxmi Kadariya");

    }
}


1 comment: