gpt4 book ai didi

java - 将两个字符串分成子字符串并将它们配对

转载 作者:行者123 更新时间:2023-12-02 11:24:32 25 4
gpt4 key购买 nike

我正在为这个问题寻找有趣的解决方案:

String key = "1;2;3;4";
String value = "Value1;Value2;Value whitespace;"

现在';'将每个值与另一个值相除。相同的符号“;”还分配键。

现在我想结束:

{"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : null}

当然,如果值大于键,则 null 不应该是该对的左侧(null:“Value5”)。

我使用 char 数组为这个问题做了一个相当复杂的解决方案,但对于很多情况和东西来说是一个很大的解决方案。(它是 O(n))。所以我很好奇看到正则表达式或子字符串解决方案或不包含大循环的东西。

编辑:我的解决方案:

private List<ExampleObject> getExampleObjects(String key , String value) {
// s
if (key == null || value == null) {
return new ArrayList<ExampleObject>();
}

List<ExampleObject> exampleObjects = new ArrayList<ExampleObject>();

char[] keyToCharArray = key.toCharArray();
char[] valueToCharArray = value.toCharArray();

StringBuilder name = new StringBuilder();
StringBuilder value = new StringBuilder();

boolean nameCompleted = false;
boolean valueCompleted = false;

for (int i = 0, j = 0; i < keyToCharArray.length || j < valueToCharArray.length;) {
if (!nameCompleted) {
char a = ' ';
try{
a = keyToCharArray[i];
} catch(Exception e){
a = ';';
// throw : VALES and key not match. More key then value
//throw(e);
}

if (a == ';' ) {
nameCompleted = true;
} else if (!(i + 1 < keyToCharArray.length)){
name.append(a);
nameCompleted = true;
} else {
name.append(a);

}
i++;
}
if (!valueCompleted) {

char a = ' ';
try{
a = valueToCharArray[j];
} catch(Exception e){
a = ';';
// throw : VALES and key not match. More value then key
//throw(e);
}

if (a == ';') {
valueCompleted = true;
} else if(!(j + 1 < valueToCharArray.length)) {
value.append(a);
valueCompleted = true;
} else {
value.append(a);
}
j++;
}
if (nameCompleted && valueCompleted) {
exampleObjects.add(new ExampleObject(name.toString(), value.toString()));
name.setLength(0);
value.setLength(0);
nameCompleted = false;
valueCompleted = false;
}
}
return exampleObjects;
}

其中ExampleObject.class具有字段keyvalue

最佳答案

我已经找到了解决您问题的方法:

输出

{"1" : "Value1", "2" : "Value2", "3" : "Value whitespace", "4" : "null"}       

代码

public class HelloWorld{

public static void main(String []args){
String key = "1;2;3;4";
String value = "Value1;Value2;Value whitespace;";

String[] keyArr = key.split(";");
String[] valueArr = value.split(";");

String finalJSON = "{";
for(int i=0; i<(keyArr.length > valueArr.length ? keyArr.length : valueArr.length); i++) {

try {
finalJSON += "\"" + keyArr[i] + "\"";
}
catch(ArrayIndexOutOfBoundsException e) {
finalJSON += "\"null\"";
}

finalJSON += " : ";

try {
finalJSON += "\"" + valueArr[i] + "\"";
}
catch(ArrayIndexOutOfBoundsException e) {
finalJSON += "\"null\"";
}
if(i!=(keyArr.length > valueArr.length ? keyArr.length : valueArr.length) - 1)
finalJSON += ", ";
}
finalJSON += "}";

System.out.println(finalJSON);
}
}

关于java - 将两个字符串分成子字符串并将它们配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38738506/

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