简体   繁体   English

java - 在字符串中找到一个整数

[英]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.正则表达式的缩写是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您可以使用 Integer.toString() 将整数转换为字符串,然后在字符串中找到它的索引

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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