我有这列名单
印度尼西亚首都雅加达。 东京,日本首都。 马尼拉,菲利普的首都。
我想去掉东京和马尼拉的主要逗号。如何编写通用代码,使其能够检测字符串是否由逗号引导并删除?
预期结果:
印度尼西亚首都雅加达。 东京,日本首都。 马尼拉,菲利普的首都。
非常感谢你的帮助。:)
发布于 2014-08-19 21:46:27
您可以使用正则表达式来完成这一任务:
for(int index = 0; index < list.size(); index++) {
String line = list.get(index);
if (line != null && line.charAt(0) == ',') {
line = line.replaceFirst("^,+");
list.set(index, line); // Replace the string in the list
}
}如果您使用的是Java 5+,它应该可以工作。
发布于 2014-08-19 21:48:47
试着做这样的事情:
String s = ",Manila, the Capital City of Phillipines.";
if( s.length() > 0 && s.trim().charAt(0) == ',' ) {
s = s.substring(s.indexOf(',')+1).trim();
}如果您必须删除多个逗号,请使用while而不是if:
String s = " , ,,Manila, the Capital City of Phillipines.";
while( s.length() > 0 && s.trim().charAt(0) == ',' ) {
s = s.substring(s.indexOf(',')+1).trim();
}发布于 2014-08-19 21:51:05
那么这个(它甚至会取代原来列表中的值):
ArrayList<String> list = new ArrayList<String>(); // This is your ArrayList
Iterator<String> it = list.iterator(); // Get your list iterator
while(it.hasNext()){ // do a while loop to manipulate the elements
String element = it.next(); // Get the next element of your list
element = element.replaceFirst("^,+"); // Remove the leading comma
it.set(element); // Replace your changed element in the list
}https://stackoverflow.com/questions/25393482
复制相似问题