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

标签 java string loops substring

我正在尝试编写一个 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/

相关文章:

java - 压缩netty发送的数据

java - 如何增加最大 JVM 线程数(Linux 64 位)

java - 如何使用 JAVA 在 HTTP GET 中设置 utf

c++ - 使用迭代器循环遍历迭代器 vector

java - 有没有办法将 "cut down"Java 对象传递给继承类?

c - 如何解析用 C 引号引起来的单词?

javascript - 不能使用 String#trim 作为 Array#map 的回调

list - 如何使用Flutter中的列表中循环添加数据

c - 如何在没有 clock_t 或定时器的情况下在 C 中执行时间循环?

java - Java中的SVG文件解析问题