-1

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?

DNA
  • 42,007
  • 12
  • 107
  • 146
Mohammed Ahmed
  • 245
  • 3
  • 4
  • 9
  • The `homework` tag is deprecated (you shouldn't use it any longer). I removed it from your question. (You can mention it in the text if you feel it's important for people to know.) For reasons it's deprecated, see http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated?cb=1 – Ken White Sep 29 '12 at 22:10

6 Answers6

9

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);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 3
    Actually you should use `StringBuilder` unless you need it to be thread-safe - [`StringBuffer` is synchronized](http://stackoverflow.com/a/355092/697449). – Paul Bellora Sep 29 '12 at 22:24
  • Cool +1 for mentioning an optimal way. – Paul Bellora Sep 29 '12 at 22:34
  • +1 Good solution - don't forget you also need to force the other characters to lowercase! – DNA Sep 29 '12 at 22:48
  • how to force the other characters to lowercase? also can it be done without StringBuilder? because I'm in a basic java class and this is the first time we using strings ! – Mohammed Ahmed Sep 29 '12 at 22:58
  • @MohammedAhmed.. I added that code.. See my updated code.. That `s1.replace` and `s2.replace` line.. – Rohit Jain Sep 29 '12 at 22:59
  • @RohitJain i did it, one more question . the names must be entered so how that can be done ? i mean the user who input the names , the names are unknown – Mohammed Ahmed Sep 29 '12 at 23:09
  • You can ask user to input name.. For that use [Scanner](http://docs.oracle.com/javase/tutorial/essential/io/scanning.html) class.. Click on the link to know more about them.. Also, you can search on google by `how to take user input through Scanner`.. – Rohit Jain Sep 29 '12 at 23:12
  • For full international title casing you should actually change the first character to title case rather than upper case. For instance the lj character becomes LJ in upper case but Lj in title case. – Neil Sep 29 '12 at 23:30
  • @Neil. Yes, but didn't considered Title case here, as OP is still a beginner.. So, might be he'll gradually learn.. But you are right.. So, will update my code, for future reference.. thanks :) – Rohit Jain Sep 29 '12 at 23:33
  • The answer below from @MadProgrammer is a better option without 2 different inputs.. – Marcello DeSales Nov 16 '13 at 17:15
  • ITs full filled my requirements.. thanks man (My requirement was convert string to Sentence case). – Amitabha Biswas Aug 21 '15 at 07:59
4

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
João Silva
  • 89,303
  • 29
  • 152
  • 158
  • 1
    @MadProgrammer: I'm assuming OP's reading a single name from the input (first and last), but that would be just a matter of `split`ting the string by `\s` and repeat the process. – João Silva Sep 29 '12 at 22:20
  • Yeah, I'm just stirring the pot. I read the OP as mean a name (which may contain spaces and possibly even hyphens), but I could just as well be wrong – MadProgrammer Sep 29 '12 at 22:44
  • In case of full name use tokenizer on space and same logic in while loop with a StringBuilder variable for new name – AlphaBetaGamma Oct 07 '14 at 12:59
  • Delimiters could be considered as stated here http://stackoverflow.com/questions/1086123/string-conversion-to-title-case – Junior Mayhé Mar 12 '16 at 16:13
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.

Community
  • 1
  • 1
Meredith
  • 3,928
  • 4
  • 33
  • 58
3

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();
}
athspk
  • 6,722
  • 7
  • 37
  • 51
elixir
  • 31
  • 1
1

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
1

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);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366