簡體   English   中英

用字符替換字符串中的字母

[英]Replacing a letter in a string with a char

String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);

我想采用變量F和L並在last和first中替換小寫的首字母,因此它們將是大寫的。 我怎樣才能做到這一點? 我只想用姓氏和姓氏替換姓氏和名字中的第一個字母

如果您嘗試做我想做的事,則應考慮使用apache commons-lang庫,然后查看:

WordUtils.capitalize

顯然,這也是開源的,因此,為尋求最佳作業解決方案,我將看一下源代碼。

但是,如果我是從頭開始編寫的(而最佳性能不是目標),這就是我的處理方法:

public String capitalize(String input)
{
    // 1. split on the negated 'word' matcher (regular expressions)
    String[] words = input.toLowerCase().split("\\W");
    StringBuffer end = new StringBuffer();
    for (String word : words)
    {
        if (word.length == 0)
            continue;
        end.append(" ");
        end.append(Character.toUpperCase(word.charAt(0)));
        end.append(word.substring(1));
    }
    // delete the first space character
    return end.deleteCharAt(0).toString();
}

編輯:
您還可以使用字符串標記器來獲取名稱,如下所示:

StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
    /* add spaces between each name */
    if(fullName != "") fullName += " ";
    currentName = st.nextToken();
    fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}

盡管有更有效的方法可以做到,但您幾乎可以做到。 您只需要將大寫字符與名字和姓氏連接起來,並禁止第一個字符。

 String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
    matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name

暫無
暫無

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

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