gpt4 book ai didi

java - 在 Java 中从列表中提取子字符串

转载 作者:行者123 更新时间:2023-12-01 16:55:04 25 4
gpt4 key购买 nike

如果我有一个父字符串(我们称之为输出),其中包含变量赋值列表,如下所示...

status.availability-state available
status.enabled-state enabled
status.status-reason The pool is available

我想提取该列表中给定变量名称的每个变量的值,即 status.availability-statestatus.enabled-state< 后面空​​格后面的子字符串status.status-reason,这样我最终得到三个不同的变量赋值,使以下每个字符串比较都为 true ...

String availability = output.substring(TODO);
String enabled = output.substring(TODO);
String reason = output.substring(TODO);

availability.equals("available");
enabled.equals("enabled");
reason.equals("The pool is available");

最简单的方法是什么?我是否应该为此使用 substring

最佳答案

这有点棘手,因为您需要将值分配给特定变量 - 您不能只拥有 Java 中变量的键映射。

我会考虑使用开关来做到这一点:

for (String line : output.split('\n')) {
String[] frags = line.split(' ', 2); // Split the line in 2 at the space.
switch (frags[0]) { // This is the "key" of the variable.
case "status.availability-state":
availability = frags[1]; // This assigns the "value" to the relevant variable.
break;
case "status.enabled-state":
enabled = frags[1];
break;
// ... etc
}
}

它不是很漂亮,但你没有太多选择。

关于java - 在 Java 中从列表中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227733/

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