In
this program, user will enter one sentence which may be of odd or even number
of words. The program is to take the words from extreme sides of the string and
generate a new string.
import
java.util.*;
import
java.io.*;
class
Str
{
String s1,s3;
String ss1[];
int m,i,j;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
StringTokenizer stk;
public void takeString()throws Exception
{
System.out.println("Enter the
string:");
s1=br.readLine();
}
public void show()
{
m=0;
stk=new StringTokenizer(s1);
ss1=new String[stk.countTokens()];
while(stk.hasMoreTokens())
{
ss1[m++]=stk.nextToken();
}
s3="";
i=0;
j=m-1;
while(i< m)
{
{
s3=s3+ " "+ss1[i]+ " "+
ss1[j];
i++;
j--;
}
if(i==j)
{
s3=s3+ " "+ ss1[i];
}
System.out.println("The modified
string="+s3);
}
public static void main(String args[])throws
Exception
{
Str ob=new Str();
ob.takeString();
ob.show();
}
}
Related Post: BlueJ Programs on String/Sentence
Details about the program
The
string is taken and the string is converted into tokens using StringTokenizer
class. According to the number of tokens in the sentences, one string type
array object is created to store the tokens. Using a while loop, the tokens
from extreme positions are appended in a string object.
Sample input and output
Enter
the string: This is a test
The
modified string= This test is a
Enter
the first string: This is a test on odd number of words
The
modified string= This words is of a number test odd on
No comments:
Post a Comment