Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取字符串的一部分_Java_Android - Fatal编程技术网

Java 获取字符串的一部分

Java 获取字符串的一部分,java,android,Java,Android,我需要在交换后获取值: 我已经开发了一种从shell命令获取输出的方法,因此我有一个字符串,它包含了图片中看到的所有内容,但是现在我只想从字符串中获取交换后的值:我如何才能做到这一点?这些值是可变的,甚至可以是所有三个0。假设文本存储在一个名为textContent的字符串中。假设交换行是字符串的最后一部分,则可以执行以下操作: int index = textContent.indexOf("Swap:"); index += "Swap:".length(); textContent.su

我需要在交换后获取值:


我已经开发了一种从shell命令获取输出的方法,因此我有一个字符串,它包含了图片中看到的所有内容,但是现在我只想从字符串中获取交换后的值:我如何才能做到这一点?这些值是可变的,甚至可以是所有三个0。

假设文本存储在一个名为textContent的字符串中。假设交换行是字符串的最后一部分,则可以执行以下操作:

int index = textContent.indexOf("Swap:");

index += "Swap:".length();
textContent.subString(index);
试试这个:

String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");

int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
    parts[i] = Integer.parseInt(stringParts[i]);

它将填充一个整数数组,并在交换部分之后填充值。

由于您已经存储了shell命令的输出,因此只需执行一些字符串操作即可搜索和提取相关信息。您可能对以下特定的字符串操作方法感兴趣:、和

下面是一个简单的示例代码,介绍如何使用上述字符串方法提取total列下的值:

public class ShellOutput {

    public ShellOutput() {
        final String extract = "Swap:"; // the keyword to search

        String shellOutput = "Swap:          75692        29657              0"; // your shell output
        int position = shellOutput.indexOf(extract); // get the position of the Swap: text
        if (position != -1) {
            String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
            String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used

            int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used

            String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number

            System.out.println("Total = " + totalNumber);
        } else {
            System.out.println("No '" + extract + "' segment found.");
        }

    }

    public static void main(String[] args) {
        new ShellOutput();
    }
}

输出:Total=75692

如何存储字符串/方法如何返回信息?图像中的三行是存储在三个不同的字符串中,还是仅存储在一个字符串中?请不要为纯文本内容发布图像。将文本直接放在你的帖子中。