我有:
String s = "NyffsGeyylB";
我需要将其更改为:
String result = "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb";
这是迄今为止我的代码:
// I use HashMap to count elements
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(i + 1, String.valueOf(s.charAt(i)));
}
// Then I convert it to list
for (Map.Entry<Integer, String> m : map.entrySet()) {
for (int i = 0; i < m.getKey(); i++) {
tempRes.add(m.getValue());
}
}
// Then I capitalize first letters and add dash
ListIterator<String> iterator = tempRes.listIterator();
while (iterator.hasNext()) {
iterator.set(iterator.next().toLowerCase());
}
result.add(tempRes.get(0).toUpperCase());
for (int i = 1; i < tempRes.size(); i++) {
if (tempRes.get(i).equalsIgnoreCase(tempRes.get(i - 1))) {
result.add(tempRes.get(i));
} else {
result.add("-");
result.add(tempRes.get(i).toUpperCase());
}
}
// And finally I add elements from result list to string:
for (int i = 0; i < result.size(); i++) {
finalResult += result.get(i);
}
结果,我得到:
"N-Yy-Fffffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyyyyyyyyyyy-Llllllllll-Bbbbbbbbbbb"
但我需要得到:
"N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb";
我怎样才能实现它?
最佳答案
for ( int i = 0 ; i < input.length() ; i++){
System.out.print(Character.toUpperCase(input.charAt(i)));
for (int j = 0; j < i; j++){
System.out.print(Character.toLowerCase(input.charAt(i)));
}
if ( i < input.length() - 1)
System.out.print("-");
}
关于java - 将字符串转换为另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74040852/