-1

公共类测试{

public static void main(String[] args) {

    String str = "My CID is #encode2#123456789#encode2# I am from India";

    String[] tokens = str.split("#encode2#");

    for (int i = 0; i < tokens.length; i++) {
        // prints the tokens
        System.out.println(tokens[i]);
    }
}

}

输出将是我的 CID 是 123456789 我来自印度

但是我只想要整个字符串中的 123456789 并且我想使用该 123456789 数字进行加密。

我也使用 if(!"#encode2#".equals(text)) 条件但仍然没有得到输出。

如何从#encode2#右侧编写条件,如需要策略并在#encode2#之前结束。

4

2 回答 2

1

使用 String 的indexOflastIndexOf方法来查找两个#encode2#子字符串开始的索引。然后,用于substring获取这两个索引之间的字符串。

String str = "My CID is #encode2#123456789#encode2# I am from India";
String substring = "#encode2#";
int firstIdx = str.indexOf(substring);
int secondIdx = str.lastIndexOf(substring);
System.out.println(str.substring(firstIdx + substring.length(), secondIdx)); //123456789
于 2021-04-23T06:19:35.253 回答
0
    public String getToken() {

        String str = "My CID is #encode2#123456789#encode2# I am from India";

        int start = str.indexOf("#encode2#") + "#encode2#".length();
        int end = str.lastIndexOf("#encode2#");

        return str.substring(start, end);
    }

注意:此方法仅在您的字符串值中有两次“#encode2#”时才有效。如果您需要多个 Token 实例,则此方法不起作用。

于 2021-04-23T06:25:02.693 回答