各位牛人进来看看
两个String字符串:
num1="one,123.0|rt,678.0|two,21.0|shi,123.0"
num2="one,45.0|shi,78.0|two,89.0|yu,84.0"
我想得到的是:
num3="one,123.0|shi,123.0|two,21.0|yu,84.0"
num1与num2里面那个‘,’前面的字符相同,就把mun2 逗号 后面的数字改成num1逗号后面的数字。
需求是这样的,他们保存的是一组物品的id和价格,格式:(id,价格|id,价格)
现在num1里面的有些物品id可能和num2里面的物品id相同,当num1里物品价格改变时,相应的num2里物品的价格也要改变、
[解决办法]
";
}
Map.Entry<String, WuPin> entry = iter.next();
result = result + entry.getKey() + "," + entry.getValue().price;
}
return result;
}
public void changeBy(Num num) {
Iterator<Entry<String, WuPin>> iter = num.wupins.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, WuPin> entry = iter.next();
if(this.wupins.containsKey(entry.getKey())){
this.wupins.get(entry.getKey()).price = entry.getValue().price;
}
}
}
class WuPin {
String id;
String price;
WuPin(String id, String price){
this.id = id;
this.price = price;
}
}
public static void main(String[] args) {
String str1="one,123.0
[解决办法]
rt,678.0
[解决办法]
two,21.0
[解决办法]
shi,123.0";
String str2="one,123.0
------解决方案--------------------
rt,678.0
[解决办法]
two,800
[解决办法]
shi,123.0";
Num num1 = new Num(str1);
System.out.println(num1);
num1.changeBy(new Num(str2));
System.out.println(num1);
}
}
[解决办法]
用 String strigs = num1.split("
[解决办法]
"); 拿到一个数组的(id,price),然后一个loop,找 indexOf(","),分别添加object。
[解决办法]
给楼主一个思路利用正则的搜索替换
public static void main(String[] args){
String num1 = "one,123.0
[解决办法]
rt,678.0
[解决办法]
two,21.0
[解决办法]
shi,123.0";
String num2 = "one,45.0
[解决办法]
shi,78.0
[解决办法]
two,89.0
[解决办法]
yu,84.0";
//捕获id以及id后面的价格为组1组2
Pttern p = Pattern.compile("\\
[解决办法]
?(.*?),(.*?)(?=\\
[解决办法]
$)");
Matcher m = p.matcher(num1);
while (m.find()) {
System.out.println(m.group(1) + "," + m.group(2));
//利用在num1中捕获到的id和价格替换num2中相同id的价格
num2=num2.replaceAll("(?<=\\Q" + m.group(1) + "\\E,).*?(?=\\
[解决办法]
$)", m.group(2));
}
System.out.println(num2);
}
public static void main(String[] args) {
String str1="One,45.0
[解决办法]
two,78.0
[解决办法]
eight,75.0
[解决办法]
three,98.0
[解决办法]
four,56.0";
String str2="five,85.0
[解决办法]
six,785.0
[解决办法]
seven,15.0
[解决办法]
eight,685.0
[解决办法]
nine,785.0
[解决办法]
One,145.0";
Num num1 = new Num(str1);
Num num2 = new Num(str2);
System.out.println(num1);
System.out.println(num2);
//num1.changeBy(num2);
//System.out.println(num1);
System.out.println("=========================================");
num2.changeBy(num1);
System.out.println(num2);
}