我有一个像这种格式的字符串
数。主题,统一名称,位置2
我想重新订购像这样的格式
Number. Uni Name, Subject, Location 2
我可以通过这种方式进行操作
int index = Order .indexOf(",");
String newStr =Order .substring(index + 1, Order .length());
但是,我认为所有字符串都有不同的名称和长度,所以可能这不起作用。所以,我的问题是如何以有效的方式动态地重新排序字符串格式?
更新问题
答案 0 :(得分:0)
String[] str = Order.split(",");
System.out.println(str[1] +","+str[0]+","+str[2]);
答案 1 :(得分:0)
您需要使用String#split()功能。Here you can find a good example 所以你可以像这样解决你的问题
String[] str = Order.split(",");
String newOrderedString = str[1] +","+str[0]+","+str[2];
//OR
newOrderedString = str[1] +","+str[2]+","+str[0];
//OR
newOrderedString = str[2] +","+str[0]+","+str[1]; // As you want
答案 2 :(得分:0)
这样的事情可行:
String s = "Subject, Uni Name, Location 2";
String[] sp = s.split(",");
String finalString = sp[1] + "," + sp[0] + "," + sp[2];
您可以考虑使用StringBuilder来执行finalString组合。
答案 3 :(得分:0)
尝试
String original = "Subject, Uni Name, Location 2";
String[] split = original.split(",");
StringBuilder b= new StringBuilder();
b.append(split[1]).append(",");
b.append(split[0]).append(",");
b.append(split[2]);
System.out.println(b.toString()); // Uni Name,Subject, Location 2
答案 4 :(得分:0)
使用:
String s = "Subject, Uni Name, Location 2";
String[] strs = s.split(",");
然后按照你需要的顺序加入结果(我已经使用trim()去掉额外的空格并将它们添加回需要的地方):
String t = strs[1].trim() + ", " + strs[0].trim() + ", " + strs[2].trim();
如果你这么做(例如在一个循环中),使用StringBuilder来构建结果字符串 - 它更有效(和惯用)。
答案 5 :(得分:0)
一种方法是正则表达式。这可能不是最的有效方式,但它相当干净:
public static void main(String args[]) {
final Pattern pattern = Pattern.compile("(\\d++)\\.([^,]++),\\s*+([^,]++),\\s*+(.*+)");
final Matcher matcher = pattern.matcher("");
//for each input string
final String input = "Subject, Uni Name, Location 2";
matcher.reset(input);
final String output = matcher.replaceAll("$1, $3, $2, $4");
System.out.println(output);
}
因此,您预先编译Pattern
并重新使用Matcher
以获得最高速度。然后,您只需对每个输入replaceAll
执行String
。
答案 6 :(得分:0)
我想说不要用这样的原始字符串做这个。使用对象。
class ReportHeader {
String number;
String name;
String subject;
String location;
ReportHeader(number,name,subject,location) {
this.number = number;
this.name = name;
this.subject = subject;
this.location = location;
}
}
class interface HeaderFormat {
String toString(ReportHeader header);
}
// this is how Wilson likes his reports
class ProfessorWilsonsHeaderFormat implements HeaderFormat {
public String toString(ReportHeader header) {
return header.number + "," + header.name + "," + header.subject + "," + header.location;
}
}
// this is how Thomspon likes his reports
class ProfessorThompsonsHeaderFormat implements HeaderFormat {
public String toString(ReportHeader header) {
return header.number + "," + header.subject + "," + header.name + "," + header.location;
}
}