「Java」String.indexOf()で指定文字が存在かどうか判定するサンプル

構文
public int indexOf(int ch)
この文字列内で、指定された文字が最初に出現する位置のインデックスを返します。
パラメータ:ch – 文字(Unicodeコード・ポイント)。
戻り値:このオブジェクトによって表される文字シーケンス内で、指定された文字が最初に出現する位置のインデックス。文字がない場合は-1。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class TargetIndexDemo {
protected static final char cft = '#';
protected static final char cft2 = '\t';
public static void main(String[] args) {
String strA = "abc#123";
String strB = "this\t is a user info";
if (strA.indexOf(cft) != -1) {
System.out.println("指定された文字が存在です、位置: " + strA.indexOf(cft));
} else {
System.out.println("不存在");
}
if (strB.indexOf(cft2) != -1) {
System.out.println("指定された文字が存在です、位置: " + strB.indexOf(cft2));
} else {
System.out.println("不存在");
}
}
}
package com.arkgame.study; public class TargetIndexDemo { protected static final char cft = '#'; protected static final char cft2 = '\t'; public static void main(String[] args) { String strA = "abc#123"; String strB = "this\t is a user info"; if (strA.indexOf(cft) != -1) { System.out.println("指定された文字が存在です、位置: " + strA.indexOf(cft)); } else { System.out.println("不存在"); } if (strB.indexOf(cft2) != -1) { System.out.println("指定された文字が存在です、位置: " + strB.indexOf(cft2)); } else { System.out.println("不存在"); } } }
package com.arkgame.study;

public class TargetIndexDemo {

      protected static final char cft = '#';
      protected static final char cft2 = '\t';

      public static void main(String[] args) {

            String strA = "abc#123";
            String strB = "this\t is a user info";
            if (strA.indexOf(cft) != -1) {
                  System.out.println("指定された文字が存在です、位置: " + strA.indexOf(cft));
            } else {
                  System.out.println("不存在");
            }
            if (strB.indexOf(cft2) != -1) {
                  System.out.println("指定された文字が存在です、位置: " + strB.indexOf(cft2));
            } else {
                  System.out.println("不存在");
            }

      }

}

結果
指定された文字が存在です、位置: 3
指定された文字が存在です、位置: 4

Java

Posted by arkgame