Format name in title case Java help please?

大兔子大兔子 提交于 2019-12-10 12:25:21

问题


so i have to write a java code to :

  • Input a name
  • Format name in title case
  • Input second name
  • Format name in title case
  • Display them in alphabet order

i know that The Java Character class has the methods isLowerCase(), isUpperCase, toLowerCase() and toUpperCase(), which you can use in reviewing a string, character by character. If the first character is lowercase, convert it to uppercase, and for each succeeding character, if the character is uppercase, convert it to lowercase.

the question is how i check each letter ? what kind of variables and strings should it be contained ? can you please help?


回答1:


You should use StringBuilder, whenver dealing with String manipulation.. This way, you end up creating lesser number of objects..

StringBuilder s1 = new StringBuilder("rohit");
StringBuilder s2 = new StringBuilder("jain");

s1.replace(0, s1.length(), s1.toString().toLowerCase());
s2.replace(0, s2.length(), s2.toString().toLowerCase());            

s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));
s2.setCharAt(0, Character.toTitleCase(s2.charAt(0)));

if (s1.toString().compareTo(s2.toString()) >= 0) {
    System.out.println(s2 + " " + s1);

} else {
    System.out.println(s1 + " " + s2);
}



回答2:


You can convert the first character to uppercase, and then lowercase the remainder of the string:

String name = "jOhN";
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); 
System.out.println(name); // John



回答3:


For traversing Strings using only the String class, iterate through each character in a string.

String s = "tester";
int size = s.length(); // length() is the number of characters in the string
for( int i = 0; i < size;  i++) {
    // s.charAt(i) gets the character at the ith code point.
}

This question answers how to "change" a String - you can't. The StringBuilder class provides convenient methods for editing characters at specific indices though.

It looks like you want to make sure all names are properly capitalized, e.g.: "martin ye" -> "Martin Ye" , in which case you'll want to traverse the String input to make sure the first character of the String and characters after a space are capitalized.

For alphabetizing a List, I suggest storing all inputted names to an ArrayList or some other Collections object, creating a Comparator that implements Comparator, and passing that to Collections.sort()... see this question on Comparable vs Comparator.




回答4:


This should fix it

List<String> nameList = new ArrayList<String>();
    nameList.add(titleCase("john smith"));
    nameList.add(titleCase("tom cruise"));
    nameList.add(titleCase("johnsmith"));
    Collections.sort(nameList);
    for (String name : nameList) {
        System.out.println("name=" + name);
    }

public static String titleCase(String realName) {
    String space = " ";
    String[] names = realName.split(space);
    StringBuilder b = new StringBuilder();
    for (String name : names) {
        if (name == null || name.isEmpty()) {
            b.append(space);
            continue;
        }
        b.append(name.substring(0, 1).toUpperCase())
                .append(name.substring(1).toLowerCase())
                .append(space);
    }
    return b.toString();
}



回答5:


String has a method toCharArray that returns a newly allocated char[] of its characters. Remember that while Strings are immutable, elements of arrays can be reassigned.

Similarly, String has a constructor that takes a char[] representing the characters of the newly created String.

So combining these, you have one way to get from a String to a char[], modify the char[], and back to a new String.




回答6:


This can be achieved in any number of ways, most of which will come down to the details of the requirements.

But the basic premise is the same. String is immutable (it's contents can not be changed), so you need away to extract the characters of the String, convert the first character to upper case and reconstitute a new String from the char array.

As has already been pointed out, this is relative simple.

The other thing you might need to do, is handle multiple names (first, last) in a single pass. Again, this is relatively simple. The difficult part is when you might need to split a string on multiple conditions, then you'll need to resort to a regular expression.

Here's a very simple example.

String name = "this is a test";
String[] parts = name.split(" ");
StringBuilder sb = new StringBuilder(64);
for (String part : parts) {
    char[] chars = part.toLowerCase().toCharArray();
    chars[0] = Character.toUpperCase(chars[0]);

    sb.append(new String(chars)).append(" ");
}

name = sb.toString().trim();
System.out.println(name);


来源:https://stackoverflow.com/questions/12656941/format-name-in-title-case-java-help-please

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!