gpt4 book ai didi

java - 将多个字符串组合成一个字符串,然后可以将其分离为原始字符串的智能方法?

转载 作者:行者123 更新时间:2023-12-01 15:29:40 24 4
gpt4 key购买 nike

假设各个字符串中可以使用的字符没有限制,并且字符串可能为空。

编辑:

似乎执行此操作的正确方法是使用分隔符,并转义任何单个字符串中已存在的分隔符。以下是我对此的尝试,它似乎有效。是否错过了任何会破坏它的情况?:

public static void main(String args[])
{
Vector<String> strings = new Vector<String>();
strings.add("abab;jmma");
strings.add("defgh;,;");
strings.add("d;;efgh;,;");
strings.add("");
strings.add("");
strings.add(";;");
strings.add(";,;");


String string = combine(strings);
strings= separate(string);
System.out.println();
}

static String combine(Vector<String> strings)
{
StringBuilder builder = new StringBuilder();

for(String string : strings)
{
//don't prepend a SEPARATOR to the first string
if(!builder.toString().equals(""))
{
builder.append(";");
}

string = string.replaceAll(";", ",;");

builder.append(string);
}

return builder.toString();
}

static Vector<String> separate(String string)
{
Vector<String> strings = new Vector<String>();

separate(string, strings, 0);

return strings;
}

static void separate(String string, Vector<String> strings, int currIndex)
{
int nextIndex = -1;
int checkIndex = currIndex;

while(nextIndex == -1 && checkIndex < string.length())
{
nextIndex = string.indexOf(';', checkIndex);
//look back to determine if this occurance is escaped
if(string.charAt(nextIndex - 1) == ',')
{
//this ones is escaped, doesn't count
checkIndex = nextIndex + 1;
nextIndex = -1;

}
}

if(nextIndex == -1)
{
//no more remain

String toAdd = string.substring(currIndex, string.length());
toAdd = toAdd.replaceAll(",;", ";");
strings.add(toAdd);
return;
}
else if(currIndex + 1 == nextIndex)
{
//empty string

strings.add("");
separate(string, strings, nextIndex);
}
else
{
//there could be more

String toAdd = string.substring(currIndex, nextIndex);
toAdd = toAdd.replaceAll(",;", ";");
strings.add(toAdd);
separate(string, strings, nextIndex + 1);
}
}

}

最佳答案

获取字符串 vector 并将其转换为 JSON 对象并存储该 JSON 对象。

( http://www.json.org/http://www.json.org/java/ )

关于java - 将多个字符串组合成一个字符串,然后可以将其分离为原始字符串的智能方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709473/

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