从字符串值读取子字符串 [英] Reading a substring from a string value

查看:144
本文介绍了从字符串值读取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Windows写了一个Java命令行应用程序,并将该cmd的结果存储在一个字符串变量中。

I wrote a Java command line application for Windows, and stored the result of that cmd in a string variable.

我的问题是:我从那里我存储了cmd的输出的变量子字符串?

My question is: Is it possible to get a substring from that variable from where I had stored the output of the cmd?

我想要一个语句创建一个操作,如果在cmd输出字符串中找到一个子字符串

I want to put a statement that creates an action if a substring is found in the cmd output string variable.

以下是应用程序类的方法:

Here are the methods of the application class:

public static void main(String[] args) throws IOException, InterruptedException
{
    runWndCommand("ping 192.168.11.3");
}

public static void runWndCommand(String cmd) throws IOException, InterruptedException
{
    Runtime runtime = Runtime.getRuntime();
    Process p = runtime.exec(new String[] { "cmd.exe", "/C", cmd });

    Scanner reader = new Scanner(p.getInputStream());

     while (reader.hasNext())
     {
        String r=reader.nextLine();
        System.out.println(r);
     }
     p.waitFor();
 }


推荐答案

在您的示例中使用 contains()

String r = reader.nextLine();

System.out.println(r);

if (r.contains("abc")) {
    System.out.println("abc found");
} else {
    System.out.println("abc not found");
}

这将打印 abc found if abc r 内的子字符串。

This will print abc found if "abc" is a substring within r.

这篇关于从字符串值读取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆