Archive

Archive for the ‘String Programs’ Category

Various String Programs

February 21, 2011 30 comments

Java provides us a good library of string functions which makes string manipulation in Java very easy and interesting.  And this skill of string manipulation is tested quite well in both ICSE (Class Xth) and ISC (Class XIIth) exams. Here is a list of some java programs written according to Bluej.  Queries regarding logic used in of any of the programs can always be asked.

For understanding strings,  click  here: Link

Removing Duplicates from the given string:

Eg. Input :  Applications

Output:  Aplictons

class Remove_Duplicates
{
    void remove(String s)
    {
        int l=s.length();
        int c;
        String org=s,  s1=””;
        for(int i=0;i<(l-1);i++)
        {
            s1=s.substring(0,i+1);
            c=0;
            for(int j=i+1; j<l;j++)
            {
                if(s.charAt(i)==s.charAt(j))
                {
                    c++;
                    continue;
                }
                else
                    s1=s1+s.charAt(j);
            }
            s=s1;
            s1=””;
            if(c>0)
                l-=c;
        }
System.out.println(“Original String:  “+org);
System.out.println(“String after removing duplicates:  “+s);
}
}

 

Finding the occurrence of a given letter in the inputted

string  in java:

import java.io.*;

class check
{void input()throws IOException
    {BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println(“Enter a sentence”);
        String s=br.readLine();
        System.out.println(“Enter the letter “);
        char a=(char)br.read();
        int len=s.length();int c=0;char x;
        for(int i=0;i
        { x=Character.toLowerCase(s.charAt(i));
            if(x==a)
                c=c+1;
        }
        System.out.println(“Frequency of the letter  ‘”+a+”‘ in the sentence ‘”+s+”‘ is “+c);
    }
}

 …………………………………………………………………………………………………………………………………………………………………………….

Program in java to accept a string and print each character

of the string along with its ASCII code:

class Ascii

{void word(String s)
   { int len=s.length();int a;char a1;
      for(int i=0;i
      { a1=s.charAt(i);
         a=a1;
         System.out.println(a1+”–>”+a);
        }
      }
  }
………………………………………………………………………………………………………………………………………………

Program to input name, middle name and surname of a person and print only the initials:

import java.io.*;

class Name
{
void input()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter your name”);
String s=br.readLine(),s1=””;
s=” “+s;
int len=s.length();
char a;
for(int i=0;i
     {
      a=s.charAt(i);
      if(a==’ ‘ )
                s1=s1+s.charAt(i+1)+”.”;
       }
System.out.println(“Initials are   ” + s1);
}
}

…………………………………………………………………………………………………………………………………………………………………………………………………………..

  Program to input name, middle name and surname of a person and print the surname followed by first name and middle name:

package aishwarya;
class Surname
{
 void input(String s)
 {
   int len=s.length();
   int in=0;
   char a;
   int last= s.lastIndexOf(‘ ‘);
   int first=s.indexOf(‘ ‘);
   String sur=s.substring(last+1);
   String middle= s.substring(first+1, last);
   String firstname= s.substring(0, first);
   System.out.println(sur+” “+firstname+” “+middle);
  }
}
………………………………………………………………………………………………………………………………………………………………

Finding Shortest and Longest Words in a String:

Pseudocode: To find the shortest and longest words in a string assuming that length of each word in the string is different. If there are two or more words with same length that happen to be the shortest or longest  words then this code gives the one that falls last in the given string.

BEGIN

INPUT a string in s.

Set str= s + ” “

SET  len to length of str

DECLARE min, max,l, word, shortest_word, longest_word and  ch

SET min to len

SET max to 0

SET word=shortest_word=longest_word=null

FOR i= 0 to < len  LOOP

SET ch to character in str at index i

IF ch is not a blank space

concatenate ch to word

ELSE

SET  l to length of word

IF  l < min

SET  min  =  l

SET shortest_word = word

ENDIF

IF  l > max

SET max = l

SET longest_word = word

ENDIF

SET word to null

ENDIF

ENDFOR

OUTPUT min, shortest-word

OUTPUT max, longest-word

END

PROGRAM CODE:

public class ShortestLongest{

public void findMethod(String s)   {

String str=s+” “;

char ch;

int len=str.length(), l=0;

int min=len,max=0;

String shortest_word=””, longest_word=””, word=””;

for(int i=0;i

ch=str.charAt(i);

if(ch!=’ ‘)    {

word+=ch;

}//if ends

else   {

l=word.length();

if(l<min)   {

min=l;

shortest_word=word;

}//if ends

if(l>max)   {

max=l;

longest_word=word;

}//if ends

word=””;

}//else ends

}//for ends

System.out.println(“Shortest word = “+ shortest_word+” with length “+min);

System.out.println(“Longest word = “+longest_word+” with length “+max);

} //method ends

}//class ends

Here is another code to find the shortest and longest words in a given string using indexOf() method.

public class ShortestLongest{

public void findMethod(String s)    {

String str=s+” “;

int len=str.length(),  l=0;

int start_index=0, last_index;

int min=len,max=0;

String shortest_word=””, longest_word=””, word=””;

while(start_index<len)   {

last_index=str.indexOf(” “, start_index);

word=str.substring(start_index,last_index);

l= word.length();

if(l<min)   {

min=l;

shortest_word=word;

}//if ends

if(l>max)   {

max=l;

longest_word=word;

}//if ends

start_index=last_index+1;

}//loop ends

System.out.println(“Shortest word = “+ shortest_word+” with length “+min);

System.out.println(“Longest word = “+longest_word+” with length “+max);

}//method ends

}//class ends

Yet another way to solve it using  StringTokenizer class of java.util package to break the entered sentence into words. StringTokenizer class has several overloaded version of constructors and one of them is ‘StringTokenizer(String s)’. This constructor breaks the string into tokens, means words with blank space as the delimitor. The function ‘nextToken()’ of StringTokenizer class is used here to access the tokens, here the words and length of each word is checked with the previous maximum length to find out the word with maximum length. The function ‘hasMoreTokens()’ of StringTokenizer class is a boolean return type function which determines whether there is any token in the StringTokenizer object or not.

import java.io.*;

import java.util.*;

public class ShortestLongest{
public void take() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //for taking inputs from user
String str1,s,maxs=””, mins=””;
StringTokenizer stk;
int len=0, lens;
System.out.println(“Enter the sentence:”);
str1=br.readLine();
lens=str1.length();
stk=new StringTokenizer(str1);while(stk.hasMoreTokens())
{
s=stk.nextToken();
if(s.length()>len)
{
len=s.length();
maxs=s;
}
if(s.length()<lens)
{
lens=s.length();
mins=s;
}
}//loop ends
System.out.println(“Word with maximum length=”+maxs);
System.out.println(“And it’s length=”+len);
System.out.println(“Word with minimum length=”+mins);
System.out.println(“And it’s length=”+lens);
}//methods ends
}//class ends
………………………………………………………………………………………………………………………………………………………………………………….

Reversing a String:

public class  Reverse

{
public static String reverseString(String s)
{
int l=s.length();
String backward=””;
for (int i=l-1; i>=0; i–)
{
backward= backward + s.charAt(i);
}
return backward;
}

public static void main(String args[])
{
String backwards = reverseString (“Allen Downey”);
System.out.println(backwards);
}}

………………………………………………………………………………………………………………………………………………….

Program to remove common characters from two strings:

import java.io.*;
public class CommonCharacters
{
public void takeStrings() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1,s2,s3=””,s4=””;
int a[],b[],x=0,y=0;
int len1,len2;
char ch;
int i,j;
System.out.println(“Enter the first sentence:”);
s1=br.readLine().trim();
System.out.println(“Enter the second sentence:”);
s2=br.readLine().trim();
len1=s1.length();
len2=s2.length();
a=new int[len1];
b=new int[len2];
for(i= 0;i< len1;i++)
{
ch=s1.charAt(i);
for(j=0;j< len2;j++)
{
if(ch==s2.charAt(j))
break;
}
if(j!=len2)
{
a[x++]=i;
b[y++]=j;
}
}
for(i=0;i< len1;i++)
{
for(j=0;j< x;j++)
{
if(i==a[j])
break;
}
if(j==x)
s3=s3+s1.charAt(i);
}
for(i=0;i< len2;i++)
{
for(j=0;j< y;j++)
{
if(i==b[j])
break;
}
if(j==y)
s4=s4+s2.charAt(i);
}
System.out.println(“Original string1=”+s1+” Modified string1=”+s3);
System.out.println(“Original string2=”+s2+” Modified string2=”+s4);
}//method ends
}//class ends
EXPLANATION:
This program is on String manipulation. Two strings are entered and initially stored in string objects. The first nested loop  loop is used to check for common characters in the strings and the common charater locations are stored in two different arrays. The second nested loop is used to search the common charater locations from the first string and those characters are skipped, remaining characters are appended on another string object. The same process is carried out on the second string object to eliminate the common characters from it.
…………………………………………………………………………………………………………………………………………………………………………………..

Program to remove vowels from a string:

import java.io.*;

public class RemoveVowel
{
public void show() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1,str2=””;
char ch,ch1;
int i,len;
System.out.println(“Enter the Sentence:”);
str1=br.readLine();
len=str1.length();
for(i=0;i< len;i++)
{
ch=str1.charAt(i);
ch1=Character.toLowerCase(ch);
switch(ch1)
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
break;
default:
str2=str2+ch;
}//switch ends
}//for ends
System.out.println(“Modified string without vowels:”+str2);
}//method ends
//to test the method show(). main() is optional in Bluej
public static void main(String args[]) throws Exception
{
RemoveVowel ob=new RemoveVowel ();
ob.show();
}//main() ends
}//class ends
EXPlANATION:
The user enters a  string including vowels (may not contain vowel also) in an object ‘str1’ of string class. Another string class object is kept in this program to hold the modified string values-without vowels. Each character is accessed and using ‘switch’, the character is checked for vowel or not. If the character is not a vowel then it is concatenated with the second string object. The same process is repeated for all characters of the entered string.

……………………………………………………………………………………………………………………………………………………………………………

Program to find the frequency of one string in another string:

import java.util.Scanner;
class FrequencyWords
{
void input()
  {
Scanner scan=new Scanner(System.in);
 System.out.println(“enter main string”);
 String s= scan.next();
 System.out.println(“enter string to be searched”);

String f= scan.next();

     s=s+” “;
    int l=s.length();
    char a; int c=0;
   String s1=””;
    for(int i=0;i<l;i++)
    { a=s.charAt(i);
       if(a!=’ ‘)
        s1=s1+a;
       else
        { if(s1.equalsIgnoreCase(f)==true)
             c++;
            s1=””;
          }
        }
     System.out.println(“Frequency of the word “+f+” is “+c);
 }
}

…………………………………………………………………………………………………………………………………………………….

Program to print all the  palindrome words in the inputted string:

class Palindrome
{
    void input(String s)
    {
        s=s+” “;
        boolean flag=true;
        int len=s.length(),in=0;
        char a,b; String s1=””;
        System.out.println(“Palindrome words : “);
        for(int i=0;i<len;i++)
        { a=s.charAt(i);
            if(a!=’ ‘)
                s1=s1+a;
            else
            { flag=true;
                in=s1.length();
                for(int j=0, k=in-1;j<(in/2); j++, k–)
                {
                    if((s1.charAt(j))== (s1.charAt(k)))
                        continue;
                    else
                    {
                        flag=false;
                        break;
                    } //else ends
                }//inner for ends
            if(flag==true)
                System.out.println(s1);
            s1=””;
           }//else ends
        }//outer for ends
    }
}
………………………………………………………………………………………………………………………………………………………………………………………………
Program to form a new word by extracting the first letter of each word in the inputted sentence:
class FirstLetter
{ void input(String s)
 {  s=” “+s;
    int len=s.length();
    char a; String s2=””;
    for(int i=0;i<len;i++)
    { a=s.charAt(i);
       if(a==’ ‘)
          s2=s2+(s.charAt(i+1));
      }
     System.out.println(“The new word –> “+s2);
    }
 }

……………………………………………………………………………………………………………………………………………………………….

Program to print the following pattern:

BLUEJ

BLUE

BLU

BL

B

class StringPattern
{
void input()
{
  String s=”BLUEJ”;
  int len=s.length();
  for(int i=5;i>=0;i–)
   System.out.println(s.substring(0,i));
    }
  }

………………………………………………………………………………………………………………………………………………………………………………..

Program to print the following pattern:

For Example:  if Input is BLUEJ

Then output is :

BBBBB

LLLL

UUU

EE

J

class PatternTwo
{ void input(String s)
  {
     char a; int j;
     int l=s.length();
     for(int i=0;i<l;i++)
     {  a=s.charAt(i);
         for(j=l-1;j>=i;j–)
         System.out.print(a);
         System.out.println();
      }
   }
}
………………………………………………………………………………………………………………………………………………………………………………..

Program to convert first letter of each word in a sentence to Uppercase and rest to lowercase:

class Covert
{ void input(String s)
 {  s=” “+s;
     String s1=””;
     char a;
    int l=s.length();
    for(int i=0;i<l;i++)
    { a=s.charAt(i);
        if(a==’ ‘)
       {
           s1=s1+a+(Character.toUpperCase(s.charAt(i+1)));
           i++;
        }
        else
        s1=s1+(Character.toLowerCase(a));
    }
    System.out.println(s1);
}
}
 ……………………………………………………………………………………………………………………………………………………………………………………………………..
FOR PRACTICE:

1. Write a program to input a sentence and print each word of the string along with its length in tabular form.

2. Write a program to input a sentence and arrange each word of the string in alphabetical order.

3. Write a program to input a sentence and arrange words of the string in order of their lengths from shortest to longest. (for class 12th)


Follow

Get every new post delivered to your Inbox.

Join 196 other followers

%d bloggers like this: