Page 1 - : Programs Related To Strings
Page 1 - : Programs Related To Strings
import java.io.*;
class Sample
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Reversing a String
Recursive Method 1 Recursive Method 2 Recursive Method 3 Without Return Type With
Return Type
void rev(String s, int i) String r=""; String r="";
{ String rev(String s, int i) String rev(String s, int i)
if(i<s.length()) { {
{ if(i<s.length()) if(i>=0)
char ch=s.charAt(i); { {
rev(s,i+1); char ch=s.charAt(i); char ch=s.charAt(i);
System.out.print(ch); rev(s,i+1); r=r+ch;
} r=r+ch; rev(s,i-1);
} }
return r; return r;
} }
In the 2nd and 3rd example we are using a recursive function with a return type and we are saving the reverse of the
String in an instance variable 'r' and we are returning the result at the end. The difference in the approach of the 2nd
and the 3rd method is that the 2nd method extracts characters from the beginning of the String and uses the LIFO
property of the stack used in recursion to reverse the word whereas, the 3rd method extracts characters from the end
of the String and adds this to the variable 'r' and does not utilize the LIFO property of the stack used in recursion.
------------------------------------ © www.javaforschool.com
-------------------------- Page 1 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
Another Recursive method Checking for Palindrome Word – ISC
String r=""; 2008
String rev(String s, int i)
{ After reversing a String using the 2nd or the 3rd method,
if(i<s.length()) you can check whether that String is a palindrome or not
{ by adding the below code in the display () function after
char ch=s.charAt(i); the printing of the reverse word:
r=ch+r;
rev(s,i+1); void display()throws IOException
} {
return r; ……
} ……
if(x.equals(s))
The above method is just a slight variation of the 2nd
System.out.print("The word is a Palindrome");
method with the only difference being that we are not
using the LIFO property and the change: r=ch+r; else
System.out.print("The word is Not a Palindrome");
}
Extracting Characters of a String and performing any given operation
Recursive Method Corresponding Iterative Method
void stringOp(String s, int i) void stringOp(String s)
{ {
if(i<s.length()) int i=0;
{ while(i<s.length())
char ch=s.charAt(i); {
char ch=s.charAt(i);
Write the operation you want to perform with
Write the operation you want to perform with
the character stored in 'ch' over here.
the character stored in 'ch' over here.
stringOp(s,i+1); i++;
} }
} }
In the above code, we are extracting the characters from the beginning of the String passed as parameter. After
storing it in the variable 'ch', you write the code of the operation you want to perform with that character. You can
also send the character to another function which will perform some task with that character.
------------------------------------ © www.javaforschool.com
-------------------------- Page 2 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
Recursive Method 2 Corresponding Iterative Method
String newstr=""; String newstr=""; int i=0;
String caseConvert(String s, int i) String caseConvert(String s)
{ {
if(i<s.length()) while(i<s.length())
{ {
char ch=s.charAt(i); char ch=s.charAt(i);
if(Character.isUpperCase(ch)) if(Character.isUpperCase(ch))
ch=Character.toLowerCase(ch); ch=Character.toLowerCase(ch);
else else
ch=Character.toUpperCase(ch); ch=Character.toUpperCase(ch);
newstr=newstr+ch; newstr=newstr+ch;
caseConvert(s,i+1); i++;
} }
return newstr; return newstr;
} }
void display()throws IOException void display()throws IOException
{ {
System.out.print("Enter any String : "); System.out.print("Enter any String : ");
String s=br.readLine(); String s=br.readLine();
String x= caseConvert(s,0); String x= caseConvert(s);
System.out.print("The new String = "+x); System.out.print("The new String = "+x);
} }
Instead of writing the case conversion code inside the recursive function, you can also send that character to
another function which is performing the case conversion. An example of this is given below: (ISC 2010)
String newstr=""; char caseConvert(char ch)
void recChange(String s, int i) {
{ if(Character.isUpperCase(ch))
if(i<s.length()) ch=Character.toLowerCase(ch);
{
else
char ch=s.charAt(i);
ch=Character.toUpperCase(ch);
newstr=newstr+caseConvert(ch);
return ch;
recChange(s,i+1); }
}
else void display()throws IOException
System.out.print("The new word = "+newstr); {
} System.out.print("Enter any word : ");
String s=br.readLine();
recChange(s,0);
}
2. Printing the initials of a name
Recursive Method Corresponding Iterative Method
void initials(String s, int i) void initials(String s)
{ {
if(i<s.length()) int i=0;
{ while(i<s.length())
char ch=s.charAt(i); {
if(ch == ' ') char ch=s.charAt(i);
System.out.print(s.charAt(i+1)+"."); if(ch == ' ')
initials(s,i+1); System.out.print(s.charAt(i+1)+".");
} i++;
} }
}
void display()throws IOException void display()throws IOException
{ {
System.out.print("Enter any name : "); System.out.print("Enter any name : ");
String s=br.readLine(); String s=br.readLine();
s=" "+s; s=" "+s;
initials(s,0); initials(s);
} }
------------------------------------ © www.javaforschool.com
-------------------------- Page 3 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
In the above program, before sending the String to the recursive function, we have added a space before the String
and then sent it. This is in accordance with the logic that the initials of a name are the characters which are just after
a space.
------------------------------------ © www.javaforschool.com
-------------------------- Page 4 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
--------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------
5. Counting Number of spaces, words, vowels, digits and consonants in a sentence
------------------------------------ © www.javaforschool.com
-------------------------- Page 5 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
--------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------
7. Printing Pattern
------------------------------------ © www.javaforschool.com
-------------------------- Page 6 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
--------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------
8. Printing Pattern
------------------------------------ © www.javaforschool.com
-------------------------- Page 7 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
9. Printing the digits of a number in words
------------------------------------ © www.javaforschool.com
-------------------------- Page 8 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
In the above recursive method alpha(), we are passing another variable 'k' which is for comparing the ASCII
values of each characters. The ASCII value of 'A' is 65, hence the starting value of variable 'k' is sent as 65 and the
value of variable 'k' goes on till 90 which is the ASCII value of 'Z'.
Inside the recursive method alpha() we have written a for-loop which will run from the starting of the String till
the end for every English alphabets i.e. this for loop will execute 26 times.
------------------------------------ © www.javaforschool.com
-------------------------- Page 9 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
Writing a return statement inside the if-block when we get a vowel, allows us to stop the execution of the
function if we get a vowel. return keyword allows us to stop the execution of a function and transfers the control
back to the calling function. In the iterative method, we are using the keyword break to stop the while loop when
we get the first vowel. In the display() method, we are printing the position of the first vowel, if the return value is not
-1, else we are printing an error message.
14. Printing and Counting the Double letter sequence present in a sentence
------------------------------------ © www.javaforschool.com
-------------------------- Page 10 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
15. Printing and Counting the Consecutive Character sequence present in a
sentence
Recursive Method Corresponding Iterative Method
int count=0; int count=0,i=0;
void consecLetter(String s, int i) void consecLetter(String s, int i)
{ {
if(i<s.length()-1) while(i<s.length()-1)
{ {
char ch1=s.charAt(i); char ch1=s.charAt(i);
char ch2=s.charAt(i+1); char ch2=s.charAt(i+1);
if((int)ch2-(int)ch1==1) if((int)ch2-(int)ch1==1)
{ {
System.out.println(ch1+","+ch2); System.out.println(ch1+","+ch2);
count++; count++;
} }
consecLetter(s,i+1); i++;
} }
} }
void display()throws IOException void display()throws IOException
{ {
System.out.print("Enter any sentence : "); System.out.print("Enter any sentence : ");
String s=br.readLine(); String s=br.readLine(); s=s.toUpperCase();
s=s.toUpperCase(); System.out.println("Consecutive letter pairs are : ");
System.out.println("Consecutive letter pairs are : "); consecLetter(s);
consecLetter(s,0); System.out.println("No. of pairs = "+count);
System.out.println("No. of pairs = "+count); }
}
If the characters are consecutive as in the English Alphabets, then the difference in the ASCII values of the 2nd
character and the 1st character will be one. This is what we are checking in the recursive function.
16. Forming a new word by taking first character of every word in a sentence
Recursive Method Corresponding Iterative Method
String newstr=""; String newstr="";
String newWord(String s, int i) String newWord(String s)
{ {
if(i<s.length()-1) int i=0;
{ while(i<s.length()-1)
char ch=s.charAt(i); {
if(ch == ' ') char ch=s.charAt(i);
newstr=newstr+s.charAt(i+1); if(ch == ' ')
newWord(s,i+1); newstr=newstr+s.charAt(i+1);
} i++;
return newstr; }
} return newstr;
}
------------------------------------ © www.javaforschool.com
-------------------------- Page 11 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
17. Finding the Piglatin of a word
In this program you first need to find the position of the first vowel. You can do this by either the recursive method or
the iterative method we discussed of finding the first vowel or you can even find the position of the first vowel inside
the display() method.
In this example we have used the recursive function for finding the first vowel.
String piggy=""; {
int vowFirst(String s, int i) char ch=s.charAt(i);
{ piggy=piggy+ch;
if(i<s.length())
piglatin(s,i+1,q);
{
}
char ch=s.charAt(i);
}
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
void display()throws IOException
{
{
return i;
} System.out.print("Enter any word : ");
return (vowFirst(s,i+1)); String s=br.readLine();
} int len=s.length();
return 0; int p=vowFirst(s,0);
} piglatin(s,p,len);
piglatin(s,0,p);
void piglatin(String s, int i, int q) piggy=piggy+"ay"; System.out.println("The
{ Piglatin of the word = "+piggy);
if(i<q) }
18. Finding the Frequency of each characters present in a word
import java.io.*; }
class Recursion void display()throws IOException
{ {
static BufferedReader br=new BufferedReader(new System.out.print("Enter any string : "); String
InputStreamReader(System.in)); s=br.readLine();
int cap[]=new int[26]; System.out.println("Character\t\tFrequency");
int sm[]=new int[26]; freqChar(s,0);
Recursion() for(int i=0;i<26;i++)
{ {
for(int i=0;i<26;i++) if(cap[i]!=0)
{ System.out.println((char)(i+65)+"\t\t\t"+cap[i]);
cap[i]=0; }
sm[i]=0; for(int i=0;i<26;i++)
} {
} if(sm[i]!=0)
void freqChar(String s, int i) System.out.println((char)(i+97)+"\t\t\t"+sm[i]);
{ }
if(i<s.length()) }
{
char ch=s.charAt(i); public static void main()throws IOException
if(ch>='A'&&ch<='Z') {
cap[ch-65]++; Recursion ob=new Recursion();
if(ch>='a'&&ch<='z') ob.display();
sm[ch-97]++; }
freqChar(s,i+1); }
}
In the above example, the array cap[] is storing the frequency of the capital letters present in the string, and the
array sm[] is storing the frequency of the small letters present in the string. In the display() method, we are
first displaying the frequencies of the capital letters and then the small letters.
------------------------------------ © www.javaforschool.com
-------------------------- Page 12 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
Extracting words of a String and performing any given operation
Recursive Method Iterative Method
String w=""; void String w=""; void
word(String s, int i) word(String)
{ {
if(i<s.length()) int i=0;
{ while(i<s.length())
char ch=s.charAt(i); {
if(ch!=' ') char ch=s.charAt(i);
{ if(ch!=' ')
w=w+ch; {
} w=w+ch;
else }
{ else
Write the operation you want to perform with {
the word stored in 'w' over here. Write the operation you want to perform with
w=""; the word stored in 'w' over here.
} w="";
word(s,i+1); }
} i++;
} }
In the code given on the left , we are extracting the characters from the beginning of the String passed as parameter
and checking whether that character stored in 'ch' is a space or not. If the character is not a space, then we add it to
the String variable 'w'. When the character is a space, then we have got a word, and hence you write what you want
to do with the word stored in 'w' in the else-block.
Important Note: While using the above code, after entering the String from the user, you need to add a space at
its end before passing it on to the recursive method.
----------------------------------- © www.javaforschool.com
----------------------------- Page 13 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
2. Printing the reverse of each word in a sentence
w=""; w="";
} }
word(s,i+1); i++;
} }
} }
----------------------------------- © www.javaforschool.com
----------------------------- Page 14 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
4. Searching for a word in a sentence
----------------------------------- © www.javaforschool.com
----------------------------- Page 15 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
Note: In both of the codes above for searching for a word or removing a word, we need to send the word we want
to search or remove also into the recursive function as a parameter.
In the code for removing a word, the recursive function is extracting one word at a time and adding it to the new string
whenever the word is not equal to the word we want to remove.
The recursive function is extracting one word at a time and checking whether that word is the same as the word we
want to replace or not. If yes, then the word is replaced with the new word and added to the new word.
----------------------------------- © www.javaforschool.com
----------------------------- Page 16 ---
JAVA FOR SCHOOL RECURSION
Making Java Fun To Learn Programs Related to Strings
---------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------
7. Printing the Piglatin of each word of a sentence
----------------------------------- © www.javaforschool.com
----------------------------- Page 17 ---