Get string index Of and handle null value - Java java.lang

Java examples for java.lang:String Index

Description

Get string index Of and handle null value

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        char searchChar = 'a';
        System.out.println(indexOf(str, searchChar));
    }/*from   w  w  w. j a v a2  s. c om*/

    public static int indexOf(String str, char searchChar) {
        if ((str == null) || (str.length() == 0)) {
            return -1;
        }

        return str.indexOf(searchChar);
    }

    public static int indexOf(String str, char searchChar, int startPos) {
        if ((str == null) || (str.length() == 0)) {
            return -1;
        }

        return str.indexOf(searchChar, startPos);
    }

    public static int indexOf(String str, String searchStr) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }

        return str.indexOf(searchStr);
    }

    public static int indexOf(String str, String searchStr, int startPos) {
        if ((str == null) || (searchStr == null)) {
            return -1;
        }

        if ((searchStr.length() == 0) && (startPos >= str.length())) {
            return str.length();
        }

        return str.indexOf(searchStr, startPos);
    }
}

Related Tutorials