Extra Practice Questions
Extra Practice Questions
Question 1
//Program : Sorting words of a String alphabetically
import java.util.*;
public class String_seq
{
String str1;
String_seq()
{ str1="";
void input()
{
void word_manip()
{
StringTokenizer st= new StringTokenizer(str1);
String a[]= new String[st.countTokens()];
int i=0;
while(st.hasMoreTokens())
{
a[i]=st.nextToken();
i++;
}
// Sorting
for(int j=0;j<a.length;j++)
{
for(int y=0;y<a.length-1;y++)
{
if(a[y].compareTo(a[y+1])>0)
{
String temp=a[y];
a[y]=a[y+1];
a[y+1]=temp;
}
}
}
}
}
OUTPUT
Enter a String
hello how are you
are hello how you
Question 2
//Program : Interchange last and first character in every word of a sentence
import java.util.*;
public class String_interchange
{
String str,final_str;
String_interchange()
{
str="";
final_str="";
}
void input()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a String");
str=sc.nextLine();
str=str +" ";
}
void Interchange()
{ String w="";
for(int i=0;i<str.length();i++)
{
char c= str.charAt(i);
if(c!=' ')
w +=c;
else
{ if( w.length()<2){
final_str +=w;
}
else
{
char c_last=w.charAt(w.length()-1);
final_str= final_str + c_last;
for(int j=1;j<w.length()-1;j++)
{
final_str +=w.charAt(j);
}
final_str +=w.charAt(0);
//final_str +=w.substring(w.length()-1) +w.substring(1,w.length()-1)
+ w.substring(0,1);
}
final_str +=" ";
w="";
}
}
}
void display()
{ System.out.println("\nUpdated String " + final_str);
Question 3
/*Program : Sorting words of a string according to their length
(using String tokenizer)*/
import java.util.*;
public class String_length_seq
{
String str1;
String_length_seq()
{ str1="";
void input()
{
void word_manip()
{
StringTokenizer st= new StringTokenizer(str1);
String a[]= new String[st.countTokens()];
int i=0;
while(st.hasMoreTokens())
{
a[i]=st.nextToken();
i++;
}
for(int j=0;j<a.length-1;j++)
{
for(int y=0;y<a.length-1;y++)
{
if(a[y].length()>a[y+1].length())
{
String temp=a[y];
a[y]=a[y+1];
a[y+1]=temp;
}
}
}
}
}
OUTPUT :
Enter a String
Believe in hard work
in hard work Believe
******************