gpt4 book ai didi

Java 在字符串中搜索子字符串除非前面有特定字符

转载 作者:行者123 更新时间:2023-11-30 07:06:14 26 4
gpt4 key购买 nike

我正在尝试编写一个 Java 程序,该程序在用户输入的字符串中搜索特定的子字符串 (xyz),并保持运行计数,除非该子字符串前面有一个句点。此时在类里面,我们只使用了 charAt 和 length,所以如果可能的话我需要坚持这一点。此外,我们根本没有使用正则表达式,所以这也是不可能的。

我已经设法让程序按预期工作,但有一个值得注意的异常(exception):如果输入的字符串以句点开头,则无法计算任何连续的匹配项。这是我到目前为止所得到的:

System.out.println("Give me a String:");
String s1 = kb.nextLine();

int index = 0;
int count = 0;

while(index <= s1.length() - 1 && s1.charAt(index) != '.')
{
if(s1.charAt(index) == 'x' && s1.charAt(index + 2) == 'z')
{
count++;
}
index++;
}
System.out.println(count);

最佳答案

You can simply check the input string whether it starts with period. If so then  you can use the following piece of code to handle the validation.

if(s1.charAt(0)!='.')
{
while(index <= s1.length() - 1 && s1.charAt(index) != '.')
{
if(s1.charAt(index) == 'x' && s1.charAt(index + 2) == 'z')
{
count++;
}
index++;
}
}
else
{
index=1;
while(index <= s1.length() - 1 && s1.charAt(index) != '.')
{
if(s1.charAt(index) == 'x' && s1.charAt(index + 2) == 'z')
{
count++;
}
index++;
}
}
System.out.println(count);
}

关于Java 在字符串中搜索子字符串除非前面有特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com