Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- `import java.util.Scanner;
- class MyString {
- String s;
- MyString() {
- s = "";
- }
- MyString(String str) {
- s = str;
- }
- void setMyString (String str) {
- s = str;
- }
- String getMyString() {
- return s;
- }
- //return the index within this.s of the first occurrence of s.
- //return -1 when s is not found on this.s.
- //if this.s = "aabababb", s = "aba", return 1
- //if this.s = "aabababb", s = "abaa", return -1
- int indexOf(String s) {
- int i=0;
- for(i = 0; i < this.s.length()-s.length(); i++) {
- for (int j = 0; j < s.length(); j++) {
- if(this.s.charAt(i+j) == s.charAt(j)) {
- i++;
- }
- else
- i=-1;
- break;
- }
- }
- return i; //going from end of string to beginning, needs fixed
- }
- //return the index within this.s of the last occurrence of s.
- //return -1 when s is not found on this.s.
- //if this.s = "aabababb", s = "aba", return 3
- //if this.s = "aabababb", s = "abaa", return -1
- // int lastIndexOf(String s) {
- // for (int i=this.s.length(); i >=0; i--) {
- // for (int j = s.length(); j>= 0; j--) {
- }
- public class Lab8 {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- MyString myS = new MyString();
- String s1, s2;// inputs
- System.out.print("Enter string 1:");
- s1 = in.nextLine();
- System.out.print("Enter string 2:");
- s2 = in.nextLine();
- myS.setMyString(s1);
- int p = myS.indexOf(s2);
- if(p==-1)
- System.out.println(s2+" not found on "+myS.getMyString());
- else
- System.out.println(s2+" found at "+p+" on "+myS.getMyString());
- p = myS.lastIndexOf(s2);
- if (p == -1)
- System.out.println(s2+" not found on "+myS.getMyString());
- else
- System.out.println(s2+" found at "+p+" on "+myS.getMyString());
- }
Add Comment
Please, Sign In to add comment