Advertisement
Guest User

Untitled

a guest
Nov 12th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. //Shamel Sameer
  2. //COMPSCIAP PERIOD 1
  3. //11/12/18
  4. //Purpose of lab is to use substrings and master the string class to replace strings and get familiar with using the string class
  5. //MR LANGSTON
  6.  
  7.  
  8. import java.util.*;
  9.  
  10. public class LAB0802
  11. {
  12. public static void main(String args[])
  13. {
  14. Scanner input = new Scanner(System.in);
  15.  
  16. String s1 = new String();
  17. String s2 = new String();
  18.  
  19. System.out.print("Please enter String 1 => ");
  20. s1 = input.nextLine();
  21. System.out.print("Please enter String 2 => ");
  22. s2 = input.nextLine();
  23. System.out.print(substitute(s1, s2) + " dat");
  24. }
  25.  
  26.  
  27. public static boolean substitute(String s1, String s2)//replaces all instances of the string 2 in string 1 using
  28. { //a series of for and while loops along with a do while loop
  29. int B=0; //also contains short circuting in case the 2nd string does
  30. int loopcount=0; //not occur at all in the first string.
  31. String s4="";
  32. boolean TF=false;
  33. boolean AB=false;
  34. do
  35. {
  36. if(s1.indexOf(s2)==-1)
  37. {
  38. System.out.println();
  39. return false;
  40. }
  41.  
  42. String s3=s1.substring(s1.indexOf(s2),s2.length()+s1.indexOf(s2));
  43. if(s3.equals(s2)==true)
  44. {
  45. s4=s4+s1.substring(0,s1.indexOf(s2));
  46. for(int K=0;K<s2.length();K++)
  47. {
  48. s4=s4+"*";
  49. }
  50. s4=s4+s1.substring(s2.length()+s1.indexOf(s2),s1.length());
  51.  
  52.  
  53. TF=true;
  54. s3="sgaydtyasfydtafsytdtfastfdtaysdftyasfdt";
  55. loopcount++;
  56. }
  57.  
  58. if (TF==true)//CHECKS IF IT HAS GONE THROUGH THE FIRST PART WHERE THE FIRST OCCURENCE HAS BEEN REPLACED
  59. {
  60. int s4index=0;
  61. while(s4.indexOf(s2)>-1)
  62. {
  63. s4index=s4.indexOf(s2);
  64. s4=s4.substring(0,s4.indexOf(s2));
  65.  
  66. for(int K=0;K<s2.length();K++)//ADDS THE "*" AT THE OCCURENCE OF S2
  67. {
  68. s4=s4+"*";
  69. }
  70. s4=s4+s1.substring(s4index+s2.length(),s1.length()) ;//REASSIGNS S4 TO BE the replaced part plus the original
  71. loopcount++;
  72.  
  73. }
  74. }
  75.  
  76.  
  77. System.out.println();
  78. System.out.print(s4);
  79. System.out.print(" "+s2+" occurs " + loopcount + " times");
  80. System.out.println();
  81. System.out.println();
  82.  
  83.  
  84.  
  85. }while(TF==false && AB==false);
  86.  
  87.  
  88. if (TF==true)
  89. return true;
  90. else if (AB==true)
  91. return false;
  92. else return false;
  93.  
  94.  
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement