[Java] Search for substrings / elements (AOJ12 --ring)

I will study using the teaching materials of AIZU ONLINE JUDGE Summarize the operations and grammar you want to perform, An example of actually answering AOJ using that grammar is posted.

Search for substrings with indexOf


public class Main {
    public static void main(String[] args){

		String str1 = "Penpineappleapplepen";
		String str2 = "pineapple";
 
		int result = str1.indexOf(str2);
 
		if (result != -1) {
		    System.out.println(str2 + "Discovery!");
			System.out.println(str2 + "Where was found:" + result);
		} else {
			System.out.println(str2 + "Was not found. .. ..");
		}
	}
}
Discover pineapple!
Where pineapple was found:3

Search for multiple elements with indexOf

import java.util.ArrayList;
import java.util.Arrays;
public class Main {
    public static void main(String[] args){

		String str1 = "Penpineappleapplepen";

        int result;
        for (int i = 0; i < str1.length(); i++) {
            result = str1.indexOf("p", i);
            if (result != -1) {
                i = result;
                System.out.println("p" + result +"Found second!");
            }
        }
	}
}
I found p third!
I found p 8th!
I found p 9th!
I found p 13th!
I found p 14th!
I found p 17th!

Ring (ITP1-8)

Create a program that determines whether a character string p can be created by selecting some characters that are continuous clockwise from an arbitrary position in the ring-shaped character string s as shown in the figure. Input The character string s is given on the first line. The character string p is given on the second line. Output If you can create p, output it to Yes, and if you cannot create it, output it to No. on one line. Constraints

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner scan=new Scanner(System.in);
        String s=scan.next();
        String p=scan.next();
        s+=s;
        if(s.indexOf(p)>=0)System.out.println("Yes");
        else System.out.println("No");
        scan.close();
    }
}

Recommended Posts

[Java] Search for substrings / elements (AOJ12 --ring)
[Java] Extract substrings (AOJ13 --shuffle)
For JAVA learning (2018-03-16-01)
Java for statement
[Java] for statement, while statement
[Java] for statement / extended for statement
Countermeasures for Java OutOfMemoryError
[Note] Java: String search
(Memo) Java for statement
NLP for Java (NLP4J) (1)
[Ruby] Searching for elements in an array using binary search