Experimenting with string in java
Posted by Samath
Last Updated: July 30, 2013
  2335

write a program that will ask user to enter N Strings/Sentences.

The problem will display each string's information:

-Number of words

-Number of Spaces

-Reversed String (by Word)

 

Sample:

Number of string : 2

Enter String 1: I am Legend

Enter String 2: Hello Java

 

Result:

String 1 : I am Legend

Number of Words: 3

Number of spaces: 2

Reverse by word: I ma dnegeL

 

String 1 : Hello Java

Number of Words: 2

Number of spaces: 1

Reverse by word: olleH avaJ

 

Screen Shot:

http://i1271.photobucket.com/albums/jj626/samath89/Untitled_zps29bc9043.png

 

http://i1271.photobucket.com/albums/jj626/samath89/javaex3_zps0631f7c8.png http://i1271.photobucket.com/albums/jj626/samath89/javaex_zps8d22b4a1.png

 

http://i1271.photobucket.com/albums/jj626/samath89/javaex4_zpsbde188e6.png

http://i1271.photobucket.com/albums/jj626/samath89/javaex5_zps32be5846.png

 

Code:

import javax.swing.JOptionPane;

public class reverse

{

      public static void main(String[] args)

      {

            String []input_message =  new String[100];;

            String input_new = "";

            int number_of_string;

            String string_holder = "";

                  string_holder  = JOptionPane.showInputDialog("Number of string");

                  number_of_string = Integer.parseInt(string_holder);

                 

                  for(int i = 1; i <= number_of_string; i++)

                  {

                        input_message[i] = JOptionPane.showInputDialog("Enter a string ");  

                  }

                  for(int i = 1; i <= number_of_string; i++)

                  {

                        int spaceCount = 0;

                        for (char c : input_message[i].toCharArray()) {

                            if (c == ' ') {

                                 spaceCount++;

                            }

                        }

                           input_new = new StringBuffer(input_message[i]).reverse().toString();

                    JOptionPane.showMessageDialog(null,"String " + i + ": "+ input_message[i] + "\n" +"Number of Words: " + input_message[i].length() + "\n" +"Number of spaces: "+ spaceCount +"\n" + "Reverse by word: "+ input_new + " ", "Result:",JOptionPane.PLAIN_MESSAGE);

                  }    

      }

}