Sunday, 16 August 2020

Return common characters of two strings using substr in java

Java program to return common characters of two strings using substring


import java.util.*;
class CommonCharacters{
    public static void main(String args[]){
    Scanner sc=new Scanner(System.in);
    System.out.println("enter first string");
    String s1=sc.nextLine();
    System.out.println("enter second string");
    String s2=sc.nextLine();
    int index;
    System.out.println("you entered first string as "+s1);
    System.out.println("you entered second string as "+s2);
    char ch;
    String str;
    for(int i=0;i<s1.length();i++){
        index=0;
         str=s1.substring(i,i+1);
        ch=str.charAt(0);//System.out.println(ch);
        index=s2.indexOf(ch);
        if(index>=0){
            System.out.println(ch);
            //s1=s1.replaceAll(""+ch,"");
            
           }
       }
    }
}

No comments:

Post a Comment