【问题标题】:printing parts of string that contains av in java在java中打印包含av的字符串部分
【发布时间】:2020-06-15 18:32:06
【问题描述】:

我正在尝试获取输入字符串并打印出包含“av”的单词

这是我的代码:

        while (true) {
        String jono = lukija.nextLine();
        String[] loydaAvSana = jono.split(" ");

        if (jono.isEmpty()) {
            System.out.println("loppu");
            break;

        }

        if(jono.contains("av")){
            for(int i = 0; i < loydaAvSana.length; i++){
                System.out.println(loydaAvSana[i]);
            }
        }

例如,如果我写:Hello World 它不应该做任何事情,但是当我写例如

“avaava ovi ava”

应该打印出来:

avaava

阿瓦

所以它应该得到包含“av”的字符串

我知道我应该使用 split 方法并且还包含方法,但我不知道如何只打印包含“av”的字符串

我的代码输出是这样的:

Hello world
ava ovi ava
ava
ovi
ava

【问题讨论】:

    标签: java split contains


    【解决方案1】:
    while (true) {
        String jono = lukija.nextLine();
        if (jono.isEmpty()) {
            System.out.println("loppu");
            break;
        }
    
        if(jono.contains("av")){
            String[] loydaAvSana = jono.split(" ");
            for(int i = 0; i < loydaAvSana.length; i++){
                if (loydaAvSana[i].contains("av") {
                    System.out.println(loydaAvSana[i]);
                }
            }
        }
    }
    
    • 阅读下一行。
    • 如果为空,则退出循环。
    • 否则,检查它是否包含“av”。
    • 如果有,请将其拆分为单词。
    • 遍历所有单词。
    • 如果单词包含“av”,则打印该单词。

    【讨论】:

      【解决方案2】:

      在你的 for 循环中,你应该插入一个 if 语句来查看数组的第 i 个元素是否包含“av”,类似于你检查整个字符串的方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-03
        • 1970-01-01
        • 2012-11-06
        • 2013-08-05
        • 2016-03-09
        • 2020-10-18
        • 1970-01-01
        • 2014-05-25
        相关资源
        最近更新 更多