tags:

views:

90

answers:

4
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);

i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last

A: 

EDIT:
You could also use a string tokenizer to get the names as in:

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);
}
gmale
It will replace every oldChar by newChar
Colin Hebert
@Colin: I thought replaceAll was the one that replaced all but after checking the API, I see you're right. Either way, replace is not the best option. Answer adjusted.
gmale
+1  A: 

if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:

WordUtils.capitalize

obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.

However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:

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();
}
pstanton
A: 

While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.

 String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
nos
A: 
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
Emil