LoginSignup
0
0

文字列の検索

文字列の内部から、別の文字列(または文字)を探すためのメソッド
2種類ある
①含まれているか否かだけの判定
②文字列のどこに含まれているかという位置情報を返すもの

メソッド定義 操作
contains ある特定の文字列(文字)が対象の文字列に含まれているか
startsWith 文字列がある特定の文字列(文字)で始まるか
endWith 文字列がある特定の文字列(文字)で終わるか
indexOf ある特定の文字列(文字)が最初に登場する位置を調べる
lastIndexOf ある特定の文字列(文字)を後ろから検索して最初に登場する位置を調べる

contains

特定の文字列(文字)が含まれているかを調べる
(大文字/小文字の区別する)
対象の文字列.contains(検索する文字列)

Main.java
public class Main {
 public static void main(String[] args) {
  String s1 = "Hello";
  System.out.println(s1.contains("e"));
  System.out.println(s1.contains("ell"));
  System.out.println(s1.contains("E"));
 }
}
結果.
true
true
false

startsWith

文字列が特定の文字列(文字)で始まるか
対象の文字列.startsWith(検索する文字列)

Main.java
public class Main {
 public static void main(String[] args) {
  String s1 = "Hello";
  String s2 = " Hello";
  System.out.println(s1.startsWith("H"));
  System.out.println(s1.startsWith("h"));
  System.out.println(s1.startsWith("He"));
  System.out.println(s2.startsWith("H"));
 }
}
結果.
true
false
true
false

endsWith

文字列が特定の文字列(文字)で終わるか
対象の文字列.endsWith(検索する文字列)

Main.java
public class Main {
 public static void main(String[] args) {
  String s1 = "Hello";
  String s2 = "Hello ";
  System.out.println(s1.endsWith("o"));
  System.out.println(s1.endsWith("O"));
  System.out.println(s1.endsWith("lo"));
  System.out.println(s2.endsWith("o"));
 }
}
結果.
true
false
true
false

indexOf

ある特定の文字列(文字)が最初に登場する位置を調べる
対象の文字列.indexOf(検索する文字列)

Main.java
public class Main {
 public static void main(String[] args) {
  String s1 = "Hello World";
  System.out.println(s1.indexOf("l"));
  System.out.println(s1.indexOf("World"));
 }
}
結果.
2
6

lastIndexOf

ある特定の文字列(文字)を後ろから検索して最初に登場する位置を調べる
対象の文字列.lastIndexOf(検索する文字列)

Main.java
public class Main {
 public static void main(String[] args) {
  String s1 = "Hello World";
  System.out.println(s1.lastIndexOf("l"));
  System.out.println(s1.lastIndexOf("World"));
 }
}
結果.
9
6
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0