简体   繁体   中英

java - find an int digit in a string

I am trying to determine whether a specific digit exists in a String, and do something if so.

See code example:

String pass = "1457";
int i = 4, j=6;
if( /* pass contains i, which is true*/)
    // ..do something
if( /* pass contains j, which is false*/)
    // ..do something

The problem is I can't find the way to do this. I have tried -

pass.indexOf(""+i)!=-1
pass.indexOf((char)(i+48))!=-1
pass.contains(""+i)==true

any suggestions?

The problem is I can't find the way to do this. I have tried -any suggestions?

Code Example : (Execution)

Here we are creating a pattern and then matching it to the string.

import java.util.regex.Pattern;

public class PatternNumber {
    public static void main(String args[]) {
        String pass = "1457";
        int i = 4, j = 6;

        Pattern p1 = Pattern.compile(".*[4].*"); // creating a regular expression pattern
        Pattern p2 = Pattern.compile(".*[6].*");
        if (p1.matcher(pass).matches()) // if match found
            System.out.println("contains : " + i);
        if (p2.matcher(pass).matches())
            System.out.println("contains : " + j);

    }
}

Output :

在此处输入图片说明

One way to do this is by using Regular Expression :

A regular expression defines a search pattern for strings. The abbreviation for regular expression is regex. The search pattern can be anything from a simple character, a fixed string or a complex expression containing special characters describing the pattern. The pattern defined by the regex may match one or several times or not at all for a given string.

Regular expressions can be used to search, edit and manipulate text.

You can use Integer.toString() to convert integer to string and then find its index in string

Refer code snippet below:-

    String pass = "1457";
    int i = 4, j = 6;
    int index = pass.indexOf(Integer.toString(i));
    if (index > -1) // index of i is 1
    {
       //do something
    }
    index = pass.indexOf(Integer.toString(j));
    if(index < 0) // index of j is -1
    {
        //do something
    }

\n
pass.chars().anyMatch(c -> c == Integer.toString(i).charAt(0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM