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,并在最后和第一个字母中替换小写的第一个字母,这样它们将是大写的。我怎样才能做到这一点?我想用char和first
替换姓氏和名字中的第一个字母答案 0 :(得分:3)
如果你想做我认为你的事,你应该考虑使用apache commons-lang库,然后看看:
显然,这也是开源的,所以为了找到最好的家庭作业解决方案,我会看一下源代码。但是,如果我是从头开始编写的(并且最佳性能不是目标),我将如何处理它:
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();
}
答案 1 :(得分:0)
编辑:
您还可以使用字符串标记生成器来获取名称,如下所示:
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);
}
答案 2 :(得分:0)
虽然有更有效的方法,但你几乎得到了它。你只需要将大写字符与名字和姓氏连接起来,然后选择第一个字符。
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
答案 3 :(得分:0)
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