在 Java 中的字符串中搜索常规子字符串



我是Java的新手。我想问一下如何在给定字符串中搜索一般子字符串。

例如:-在
字符串12345.67中,我想搜索子字符串 .67
在字符串 1.00 中,我想搜索字符串.00

我基本上想搜索部首(.(之后的字符串,前提是部首之后的字符数只有2个。

根据我的知识,搜索一般子字符串是不可能的,因此我请求您的帮助。

我希望将输入(存储在数据库中(打印为浮点数,转换为印度货币格式,即逗号分隔。
我什至查看了以前的各种帖子,但似乎都没有帮助我,因为几乎每个人都无法产生小数点的重音输出

根据我的知识,搜索一般子字符串是不可能的

所以你可能会学到更多,这里是String substring(int beginIndex)方法:

String str = "12345.67";
String res = str.substring(str.indexOf('.')); // .67

如果要检查.后是否只有 2 位数字:

String str = "12345.67";
String res = str.substring(str.indexOf('.') + 1); // 67
if(res.length() == 2)
System.out.println("Good, 2 digits");
else
System.out.println("Holy sh** there isn't 2 digits);

您可以使用拆分和子字符串来实现您的目标

String test = "12345.67";
System.out.println(test.split("\.")[1].substring(0,2));

在拆分函数中,您可以传递可用于提供分隔符的正则表达式,并在子字符串函数中传递要提取的字符数

在@azro提供的答案旁边,您还可以使用正则表达式:

String string = "12345.67";
Pattern ppattern = Pattern.compile("\d+(\.\d{2})");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String sub = matcher.group(1);
System.out.println(sub);
}

哪些打印:

.67
String str = "12345.67";
String searchString = "." + str.split("\.")[1];
if(str.contains(searchString)){
System.out.println("The String contains the subString");
}
else{
System.out.println("The String doesn't contains the subString");
}

最新更新