Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Shamel Sameer
- //COMPSCIAP PERIOD 1
- //11/12/18
- //Purpose of lab is to use substrings and master the string class to replace strings and get familiar with using the string class
- //MR LANGSTON
- import java.util.*;
- public class LAB0802
- {
- public static void main(String args[])
- {
- Scanner input = new Scanner(System.in);
- String s1 = new String();
- String s2 = new String();
- System.out.print("Please enter String 1 => ");
- s1 = input.nextLine();
- System.out.print("Please enter String 2 => ");
- s2 = input.nextLine();
- System.out.print(substitute(s1, s2) + " dat");
- }
- public static boolean substitute(String s1, String s2)//replaces all instances of the string 2 in string 1 using
- { //a series of for and while loops along with a do while loop
- int B=0; //also contains short circuting in case the 2nd string does
- int loopcount=0; //not occur at all in the first string.
- String s4="";
- boolean TF=false;
- boolean AB=false;
- do
- {
- if(s1.indexOf(s2)==-1)
- {
- System.out.println();
- return false;
- }
- String s3=s1.substring(s1.indexOf(s2),s2.length()+s1.indexOf(s2));
- if(s3.equals(s2)==true)
- {
- s4=s4+s1.substring(0,s1.indexOf(s2));
- for(int K=0;K<s2.length();K++)
- {
- s4=s4+"*";
- }
- s4=s4+s1.substring(s2.length()+s1.indexOf(s2),s1.length());
- TF=true;
- s3="sgaydtyasfydtafsytdtfastfdtaysdftyasfdt";
- loopcount++;
- }
- if (TF==true)//CHECKS IF IT HAS GONE THROUGH THE FIRST PART WHERE THE FIRST OCCURENCE HAS BEEN REPLACED
- {
- int s4index=0;
- while(s4.indexOf(s2)>-1)
- {
- s4index=s4.indexOf(s2);
- s4=s4.substring(0,s4.indexOf(s2));
- for(int K=0;K<s2.length();K++)//ADDS THE "*" AT THE OCCURENCE OF S2
- {
- s4=s4+"*";
- }
- s4=s4+s1.substring(s4index+s2.length(),s1.length()) ;//REASSIGNS S4 TO BE the replaced part plus the original
- loopcount++;
- }
- }
- System.out.println();
- System.out.print(s4);
- System.out.print(" "+s2+" occurs " + loopcount + " times");
- System.out.println();
- System.out.println();
- }while(TF==false && AB==false);
- if (TF==true)
- return true;
- else if (AB==true)
- return false;
- else return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement