簡體   English   中英

我想在 Java 中刪除特殊字符並將下一個字母轉換為大寫“the-stealth-warrior”

[英]I want to remove the special character and convert the next letter to uppercase "the-stealth-warrior" in Java

public class Main {
    public static void main(String[] args) {
      String name = "the-stealth-warrior";
      for (int i = 0; i < name.length();i++){
         if (name.charAt(i) == '-'){
             char newName = Character.toUpperCase(name.charAt(i+1));
             newName += name.charAt(i + 1);
             i++;
         }
      }
    }
}

我嘗試循環輸入每個字符並檢查 I == '-' 是否將下一個字母轉換為大寫,並將 append 轉換為新字符串。

我們可以在 stream 的幫助下嘗試使用拆分方法:

String name = "the-stealth-warrior";
String parts = name.replaceAll("^.*?-", "");
String output = Arrays.stream(parts.split("-"))
                      .map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
                      .collect(Collectors.joining(""));
output = name.split("-", 2)[0] + output;
System.out.println(output);  // theStealthWarrior

我認為最簡潔的方法是使用正則表達式:

String newName = Pattern.compile("-+(.)?").matcher(name).replaceAll(mr -> mr.group(1).toUpperCase());

請注意, Pattern.compile(...)可以存儲而不是每次都重新評估它。

更詳細(但可能更有效的方法)是使用StringBuilder構建字符串:

StringBuilder sb = new StringBuilder(name.length());
boolean uc = false;  // Flag to know whether to uppercase the char.
int len = name.codePointsCount(0, name.length());
for (int i = 0; i < name.len; ++i) {
  int c = name.codePointAt(i);
  if (c == '-') {
    // Don't append the codepoint, but flag to uppercase the next codepoint
    // that isn't a '-'.
    uc = true;
  } else {
    if (uc) {
      c = Character.toUpperCase(c);
      uc = false;
    }
    sb.appendCodePoint(c);
  }
}
String newName = sb.toString();

請注意,您不能可靠地將特定語言環境中的單個代碼點大寫,例如Locale.GERMAN中的ß

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM