Java String Manipulation Programs


Java / Friday, August 17th, 2018

Java String Manipulation

Today I am going to discuss about some java string manipulation programs. The programs that I am discussing are of basic to intermediary levels. I assume that you have some knowledge about java string class and its methods, if not you can learn it from by post on Java string class.

In the first program I will show working of some of the java string class methods. Let’s try

 Program 01
/**
 *
 * @author Rajib
 */

public class StringManipulation {
    public static void main(String[] args) 
    {        
        String a="Sourav";
        String b="computer";
        String c="easy understanding";
        String d="Rajib Kumar Saha";
        String e=" rajib Kumar Saha";
        String f="Subrata Das";
        String g = "COMPUTER";
        
        System.out.println("The upper case of "+a+" is = "+a.toUpperCase());
        System.out.println("The upper case of "+b+" is = "+b.toUpperCase());
        System.out.println("The lower case of "+g+" is = "+g.toLowerCase());       
        
        
        System.out.println("After replacing m with n of "+b+" we get "+b.replace('m','n'));        
        System.out.println("Gupta".replace('G', 'L'));
        
        System.out.println("The string after removing blank spaces = "+c.trim());
        System.out.println("The equal string = "+d.equals(e.trim()));
        System.out.println("The equal string = "+d.equalsIgnoreCase(e.trim()));
        
        System.out.println("The length of "+e+ " = "+e.length());
        System.out.println("The charecter at 5th position of "+b+" = "+b.charAt(5-1));
        
        System.out.println("The substring from the 6th index: "+c.substring(6));
        System.out.println("The substring out of 9, leaving first 4 characters: "+c.substring(4,9));
        
        System.out.println("The first occurence of the character 'a': "+d.indexOf('a'));
        System.out.println("The index of 'a' from 5th character: "+d.indexOf('a', 5));
        
        System.out.println("The compare string: "+d.compareTo(e.trim()));
        System.out.println("The compare without case string: "+d.equalsIgnoreCase(e.trim()));
    } 
}

Output:

The upper case of Sourav is = SOURAV
The upper case of computer is = COMPUTER
The lower case of COMPUTER is = computer
The value of Sourav
After replacing m with n of computer we get conputer
Lupta
The string after removing blank spaces = easy understanding
The equal string = false
The equal string = true
The length of rajib Kumar Saha = 17
The charecter at 5th position of computer = u
The substring from the 6th index: nderstanding
The substring out of 9, leaving first 4 characters: unde
The first occurence of the character ‘a’: 1
The index of ‘a’ from 5th character: 9
The compare string: -32
The compare without case string: true

Note: To take input from the user I am using Scanner class. If you don’t know how the Scanner class works, then follow the link.

 Program 02

Write a program to display the given pattern.
R
RA
RAJ
RAJI
RAJIB

/**
 *
 * @author Rajib
 */
import java.util.*;

public class Pattern1 {
    public static void main(String k[]){
        Scanner sc = new Scanner(System.in);
        int i,len;
        
        System.out.println("Enter your word to show the pattern: ");
        String str = sc.next();
        len = str.length();
        
        for(i=0;i<=len;i++){
            System.out.println(str.substring(0,i));
        }
        
    }
}

Output:

Enter your word to show the pattern:
RAJIB

R
RA
RAJ
RAJI
RAJIB

 Program 03

Write a program to display the given pattern.
Pattern2

 

 

/**
 *
 * @author Rajib
 */
import java.util.*;
public class Pattern2 {
    public static void main(String k[]){
        Scanner sc = new Scanner(System.in);
        int i,j,len,m=1;
        
        System.out.print("Enter your word to show the pattern: ");
        String str = sc.next();
        len = str.length();
        
        for(i=len;i>=0;i--){
            for(j=1;j<=m;j++){
                System.out.print(" ");
            }
            System.out.println(str.substring(0,i));
            m++;
        }
        
    }
}

Output:

Enter your word to show the pattern: RAJIB
Pattern2

 

 

 

 Program 04

Write a program to display the given pattern.
LIVEDU
IVEDUL
VEDULI
EDULIV
DULIVE
ULIVED

/**
 *
 * @author Rajib
 */
import java.util.Scanner;
public class Pattern3 {
    public static void main(String k[]){
        Scanner sc = new Scanner(System.in);
        int i,j,len;
        
        System.out.print("Enter your word to show the pattern: ");
        String str = sc.next();
        len = str.length();
        
        for(i=0;i<len;i++){
            System.out.print(str.substring(i,len));
            System.out.print(str.substring(0,i));
            System.out.println();
        }        
    }
}

Output:

Enter your word to show the pattern: LIVEDU
LIVEDU
IVEDUL
VEDULI
EDULIV
DULIVE
ULIVED

 Program 05

Write a program to accept a string. Count and display the number of vowels present in the String.

/**
 *
 * @author Rajib
 */

import java.util.*;
public class VowelCount 
{  
    public static void main(String args[])
    {        
        Scanner sc=new Scanner(System.in);        
        int counter=0,i;
        char temp;
        
        System.out.print("Enter any string: ");        
        String str=sc.nextLine();
       
        for(i=0;i<str.length();i++)
        {
            temp=str.charAt(i);            
            if(temp=='A' || temp=='a' || temp=='E'|| temp=='e' || temp=='I' || 
                    temp=='i' || temp=='O' || temp=='o' || temp=='U' || temp=='u')
            {                
                counter=counter+1;                
            }
        }
        System.out.println("The number of vowel present in "+ str +" is "+counter);
    }  
}

Output:

Enter any string: I love Java
The number of vowel present in I love Java is 5

 Program 06

Write a program to accept a string in lower case and replace ‘e’ with ‘*’ in the given string. Display the new string.

/**
 *
 * @author Rajib
 */
import java.util.*;
public class ReplaceChar {
    public static void main(String k[]){
        Scanner sc = new Scanner(System.in);
        int i, len;   
        char ch;
        String rep_str="";
        
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        len = str.length();
        
        for(i=0;i<len;i++){
            ch = str.charAt(i);
            if(ch=='e')
                ch='*';
            rep_str = rep_str + ch;
        }
        System.out.println("The new String is "+rep_str);
    }
}

Output:

Enter a string: computer science
The new String is comput*r sci*nc*

 Program 07

Write a program to accept a string and change the case of each letter of the string. Display the new string.

/**
 *
 * @author Rajib
 */
import java.util.*;
public class ChangeCase {
    public static void main(String []k){
        Scanner sc = new Scanner(System.in);
        int i,j, len;
        String st,str="";
        char ch,chr=' ';
        
        System.out.print("Enter your string: ");
        st = sc.nextLine();
        len = st.length();
        
        for(i=0;i<len;i++){
            ch=st.charAt(i);
            if(Character.isLowerCase(ch)){
                chr = Character.toUpperCase(ch);
                str = str + chr;
            }
            else if(Character.isUpperCase(ch)){
                chr = Character.toLowerCase(ch);
                str = str + chr;
            }
            else
                str = str + ch;
        }
        System.out.println("The string before converting the case of each alphabet: "+st);
        System.out.println("The string after converting the case of each alphabet: "+str);
    }
}

Output:

Enter your string: String Manipulation Programs in Java
The string before converting the case of each alphabet: String Manipulation Programs in Java
The string after converting the case of each alphabet: sTRING mANIPULATION pROGRAMS IN jAVA

 Program 08

Write a program to accept a name and display the initials along with the surname.

/**
 *
 * @author Rajib
 */
import java.util.*;
public class Initials {
    public static void main(String []k){
        Scanner sc = new Scanner(System.in);
        String st, str, str1="", str2="";
        int i,j;
        char ch;
        
        System.out.print("Enter full name: ");
        st = sc.nextLine();
                
        st = ' ' + st;
        j = st.lastIndexOf(' ');    //obtain the last blank's index
        str = st.substring(j);      //extract the surname
        
        for(i=0;i<j;i++){           //extract initial from each word
            ch = st.charAt(i);
            if(ch==' ')
                str1 = str1 + st.charAt(i+1) + '.';
        }
        str2 = str1 + str;          //concatenate initials and surname
        System.out.println("You have entered the name: " + st);
        System.out.println("Name as initial with surname: " + str2);
    }
}

Output:

Enter full name: Rajib Kumar Saha
You have entered the name: Rajib Kumar Saha
Name as initial with surname: R.K. Saha

 Program 09

Write a program in Java to accept a sentence and a word that present in the sentence. Find and print the frequency of the given word in the sentence.

/**
 *
 * @author Rajib
 */
import java.util.*;
public class WordFrequency {
    public static void main(String k[]){
        String st, str="", str1="";
        int i, len, f=0;
        char ch;
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        st = sc.nextLine();
        System.out.print("Enter a word to be searched in the string: ");
        str = sc.nextLine();
        
        st = st + ' ';
        len = st.length();
        
        for(i=0;i<len;i++){
            ch = st.charAt(i);
            if(ch==' '){
                if(str1.compareTo(str)==0)
                    f = f + 1;
                str1="";
            }
            else
                str1 = str1 + ch; 
        }
        System.out.println("Frequency of searched word present in the string: "+f);
    }
}

Output:

Enter a string: the quick brown fox jumps over the lazy dog
Enter a word to be searched in the string: the
Frequency of searched word present in the string: 2

 Program 10

Write a program in Java to accept a word and display the same in Pig Latin from

Pig Latin: A word is said to be in Pig Latin form when it is obtained by forming a new word by placing the four vowel of the original word at the start of the new word along with the letters following it. The letters present before the first vowel are shifted to the end of the new word, followed by ‘ay’.

/**
 *
 * @author Rajib
 */
import java.util.*;
public class PigLatin {
    public static void main(String k[]){
        int i, len;
        String st,str,str1,str2;
        char temp;
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the string: ");
        st = sc.nextLine();
        len = st.length();
        
        for(i=0;i<len;i++){
            temp = st.charAt(i);
            if(temp=='A' || temp=='a' || temp=='E'|| temp=='e' || temp=='I' || 
                    temp=='i' || temp=='O' || temp=='o' || temp=='U' || temp=='u')
                break;
        }
        str = st.substring(i, len);
        str1 = st.substring(0, i);
        str2 = str + str1 + "ay";
        
        System.out.println("The Pig Latin form of the given string: "+str2);
    }
}

Output:

Enter the string: trouble
The Pig Latin form of the given string: oubletray

*  Try to understand yourself….if any doubt comes write comment then I will solve your doubt.

** If you find problem solving any string related program, comment it or send it to me, I will love to help you.

 

<< Previous     Next>>

 

 ;

Leave a Reply

Your email address will not be published. Required fields are marked *