我有字符串b="Name=Paul Roberts|Telephone=|Address=|City=LA";
我一直在努力获得输出属性 - 值对而没有相同的和管道符号。我有超过4个结果,但这是我想要实现的:
输出(将每对分开,因为我必须将这两个值放入某些表的字段中):
Name
Paul Roberts
Telephone
Address
City
LA
所以你可以注意到VALUE可以为null(空)。
我尝试使用SUBSTRING(可能有更好的方法)但是得到了错误的结果:
static String b="Name=Paul Roberts|Telephone=|Address=|City=LA";
public static void main(String[] args) {
System.out.println("b="+b);
String match = "=";
int i =0;
while((i=(b.indexOf(match,i)+1))>0)
{
String c=b.substring(0,i-1);
String d=b.substring(i);
String match2="|";
int k=b.indexOf(match2);
System.out.println("Attribute="+c);
int j=d.indexOf(match2);
if (j>-1)
{
String e=d.substring(0,j);
System.out.println("Value="+e);
}
if (k>-1)
{
b=b.substring(k+1,b.length());
}
}
}
我接近正确的结果,但这就是我得到的:
b=Name=Paul Roberts|Telephone=|Address=|City=LA
Attribute=Name
Value=Paul Roberts
Attribute=Telephone
Value=
Attribute=Address=|City
所以你可以注意到最后一行不正确,我错过了两行。 这也是SUBSTRING最有效的方式吗?
答案 0 :(得分:3)
拆分字符串使这更容易:
public static void main(String[] args) {
String b="Name=Paul Roberts|Telephone=|Address=|City=LA";
for (String s : b.split("\\|")) {
String[] pair = s.split("=");
String attribute = pair[0];
String value = ((pair.length > 1) ? pair[1] : "");
System.out.println("Attribute=" + attribute);
System.out.println("Value=" + value);
System.out.println();
}
}
输出:
Attribute=Name Value=Paul Roberts Attribute=Telephone Value= Attribute=Address Value= Attribute=City Value=LA
答案 1 :(得分:0)
这样做的基本方法是
String b="Name=Paul Roberts|Telephone=|Address=|City=LA";
b = b.replace("\"", "");
b = b.replace("|", "\n");
b = b.replace("=", "\n");
System.out.println(b);
输出
Name
Paul Roberts
Telephone
Address
City
LA
如果您使用StringBuffer
而不是直接操作字符串,那将会更好。