簡體   English   中英

如何使用Java將字符串中的所有字母替換為另一個字符?

[英]How do I replace all the letters in a string with another character using Java?

我希望能夠用下划線字符替換字符串中的所有字母。

例如,假設我的字符串由字母字符“ Apple”組成。 因為蘋果里面有五個字符(字母),我如何將其轉換為五個下划線?

為什么不忽略“替換”的想法,而只創建一個帶有相同下划線數量的新字符串...

String input = "Apple";

String output = new String(new char[input .length()]).replace("\0", "_");
//or
String output2 = StringUtils.repeat("_", input .length());

很大程度上是從這里開始的

正如許多其他人所說的那樣,如果您不想包含空格,則replaceAll可能是解決之道。 為此,您不需要正則表達式的全部功能,但除非字符串絕對很大,否則肯定不會受到傷害。

//replaces all non-whitespace with "_"
String output3 = input.replaceAll("\S", "_");
        String content = "apple";
        String replaceContent = "";
        for (int i = 0; i < content.length(); i++)
        {
            replaceContent = replaceContent + content.replaceAll("^\\p{L}+(?: \\p{L}+)*$", "_");
        }

        System.out.println(replaceContent);

使用正則表達式

關於\\p{L} :參考Unicode正則表達式

您可以使用String.replaceAll()方法。

替換所有字母:

String originalString = "abcde1234";
String underscoreString = originalString.replaceAll("[a-zA-Z]","_");

如果您的意思是所有字符:

String originalString = "abcde1234";
String underscoreString = originalString .replaceAll(".", "_");

那這個呢

  public static void main(String args[]) {
    String word="apple";

        for(int i=0;i<word.length();i++) {
            word = word.replace(word.charAt(i),'_');
        }
        System.out.println(word);
}

試試這個。

String str = "Apple";
str = str.replaceAll(".", "_");
System.out.println(str);

嘗試這個,

        String sample = "Apple";
        StringBuilder stringBuilder = new StringBuilder();
        for(char value : sample.toCharArray())
        {
            stringBuilder.append("_");
        }
        System.out.println(stringBuilder.toString());
stringToModify.replaceAll("[a-zA-Z]","_");

你可以做

int length = "Apple".length();
String underscores = new String(new char[length]).replace("\0", "_");

str.replaceAll("[a-zA-Z]","_");


    String str="stackoverflow";
    StringBuilder builder=new StringBuilder();
    for(int i=0;i<str.length();i++){
        builder.append('_');
    }
    System.out.println(builder.toString());

當然,我可以選擇其他方法:

String input = "Apple";
char[] newCharacters = new char[input.length()];
Arrays.fill(newCharacters, '_');
String underscores = new String(newCharacters);

或者這是一種不錯的遞歸方法:

public static void main(String[] args) {
    System.out.println(underscores("Apple"));
}

public static String underscores(String input) {
    if (input.isEmpty()) return "";
    else return "_" + underscores(input.substring(1));
}

暫無
暫無

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

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