Guest User

Untitled

a guest
Oct 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. `import java.util.Scanner;
  2. class MyString {
  3. String s;
  4.  
  5. MyString() {
  6. s = "";
  7. }
  8.  
  9. MyString(String str) {
  10. s = str;
  11. }
  12.  
  13. void setMyString (String str) {
  14. s = str;
  15. }
  16.  
  17. String getMyString() {
  18. return s;
  19. }
  20.  
  21. //return the index within this.s of the first occurrence of s.
  22. //return -1 when s is not found on this.s.
  23. //if this.s = "aabababb", s = "aba", return 1
  24. //if this.s = "aabababb", s = "abaa", return -1
  25. int indexOf(String s) {
  26. int i=0;
  27. for(i = 0; i < this.s.length()-s.length(); i++) {
  28. for (int j = 0; j < s.length(); j++) {
  29. if(this.s.charAt(i+j) == s.charAt(j)) {
  30. i++;
  31. }
  32. else
  33. i=-1;
  34. break;
  35. }
  36. }
  37. return i; //going from end of string to beginning, needs fixed
  38. }
  39.  
  40. //return the index within this.s of the last occurrence of s.
  41. //return -1 when s is not found on this.s.
  42. //if this.s = "aabababb", s = "aba", return 3
  43. //if this.s = "aabababb", s = "abaa", return -1
  44. // int lastIndexOf(String s) {
  45. // for (int i=this.s.length(); i >=0; i--) {
  46. // for (int j = s.length(); j>= 0; j--) {
  47.  
  48. }
  49.  
  50. public class Lab8 {
  51. public static void main(String[] args) {
  52. Scanner in = new Scanner(System.in);
  53. MyString myS = new MyString();
  54.  
  55. String s1, s2;// inputs
  56.  
  57. System.out.print("Enter string 1:");
  58. s1 = in.nextLine();
  59. System.out.print("Enter string 2:");
  60. s2 = in.nextLine();
  61.  
  62. myS.setMyString(s1);
  63.  
  64. int p = myS.indexOf(s2);
  65. if(p==-1)
  66. System.out.println(s2+" not found on "+myS.getMyString());
  67. else
  68. System.out.println(s2+" found at "+p+" on "+myS.getMyString());
  69.  
  70. p = myS.lastIndexOf(s2);
  71. if (p == -1)
  72. System.out.println(s2+" not found on "+myS.getMyString());
  73. else
  74. System.out.println(s2+" found at "+p+" on "+myS.getMyString());
  75. }
Add Comment
Please, Sign In to add comment