Home > Back-end >  Name Formatting in Java
Name Formatting in Java

Time:10-07

public static void main(String[] args) {
    
    Scanner input = new Scanner(System.in);
    String userInput ="";
System.out.println("Enter firstName middleName lastName separated by at least one blank, It may have more than one blank separating firstName middleName lastName");


    userInput = input.nextLine();
    String firstName ="";
    String middleName ="";
    String lastName ="";

    int firstSpace = userInput.indexOf(' ');
    int secondSpace = userInput.lastIndexOf(' ');
    firstName = userInput.substring(0,firstSpace);
    System.out.println("Value of First:"  firstName   "     Second:" secondSpace);
        
    if(secondSpace >= 0)// for if there are only first, last names, which is 2 names
    {
      
      lastName = userInput.substring(secondSpace 1);
      lastName = lastName.trim();
      System.out.println(lastName  ", "   firstName.charAt(0));
    }
    else// case if input contains 3 names
    {
      middleName = userInput.substring(firstSpace 1, secondSpace);
      middleName = middleName.trim();
      lastName = userInput.substring(secondSpace 1,userInput.length());
      System.out.println(lastName ", "  firstName.charAt(0) '.' middleName.charAt(0) '.');
    }
    
}

I am trying to extract (LastName, FirstName Initial) as well as (LastName, MiddleName Initial.FirstName Initial).

However, for the case of having only First, Last name I have tried

if(secondSpace < 0), but this is not suitable since it always has 2 blanks in case of typing "Phone (empty spaces) Apple", I don't know how to set the condition check.

Any advice on this matter?

I am not allowed to use "Split, array, String Buffer, String Builder".

CodePudding user response:

You can do this using variants of String#substring() (substring(int beginIndex, int endIndex) and substring(int beginIndex)) and the String#indexOf() methods. In particular the indexOf(int ch, int fromIndex) method.

Scanner input = new Scanner(System.in);
String userInput = "";
System.out.println("Enter:  FirstName MiddleName LastName  separated by ");
System.out.println("at least one blank. You may have more than one blank");
System.out.print  ("separating the name components: -> ");

userInput = input.nextLine().replaceAll("\\s ", " ");
    
String firstName = "", middleName = "", lastName = "";
firstName =  userInput.substring(0, userInput.indexOf(' ', 0)).trim();
if (userInput.replaceAll("[^ ]", "").length() == 1) {
    middleName = ""; 
    lastName = userInput.substring(userInput.indexOf(' ', 0)).trim();
}
else {
    middleName = userInput.substring(userInput.indexOf(' '), 
                                 userInput.indexOf(' ', firstName.length()   1)).trim();
    lastName = userInput.substring(firstName.length()   middleName.length()   1).trim();
}
System.out.println(firstName   " "   (middleName.isEmpty() ? lastName : middleName   " "   lastName));

Here is the same code again with a bunch of obtrusive commenting which explains everything. Of course the comments can be deleted but give them a read first:

Scanner input = new Scanner(System.in);
String userInput = "";
System.out.println("Enter:  FirstName MiddleName LastName  separated by ");
System.out.println("at least one blank. You may have more than one blank");
System.out.print  ("separating the name components: -> ");

/* Get User supploed Name but once it's entered....
   Get rid of any excessive spacing or tabbing (if any). We only want 
   a single whitespace between each name (however many there are). The 
   `String#replaceAll()` method is used for this with a small Regular 
   Expression (regex) "\\s ". This will replace any locations within 
   the string which contains 1 or more whitespaces (or tabs) with a 
   single whitespace.                       */
userInput = input.nextLine().replaceAll("\\s ", " ");
        
String firstName = "", middleName = "", lastName = "";
        
/* Get the First Name:
   Notice the overloaded version of the indexOf() method we're using. 
   We are taking advantage of the `fromIndex` parameter (see javaDoc
   for the String#indexOf() method). We're forcing the indexOf() method
   to retrieve the index value for the first encoutered whitespace 
   character within the input string starting from index 0. We really
   don't need this to get the first name but...what the heck, it's good
   to see how this starts.                                     */
   firstName =  userInput.substring(0, userInput.indexOf(' ', 0)).trim();
        
/* Get the Middle Name...but wait:
   Let's see if two names (First & Last) OR if three names (First, 
   middle, and last) are given by the User. To do this we need to 
   count the number of whitespaces contained withn the name that 
   was input by the User. If there is only `one` whitespace then that 
   means that there are only two names supplied which must First and 
   Last names. If there are `two` whitespaces then there must be three
   names provided by the User and so on. To count the number of spaces 
   within the User supplied Name we again utilize the String#replaceAll()
   method with again, another small regex which basically simulates the
   deletion of all characters within the supplied name string except 
   for whitespaces. The String#length() method is also applied so to 
   get the remaining length of characters which are now all whitespaces. */
if (userInput.replaceAll("[^ ]", "").length() == 1) {
    // Yup, only two names (First & Last)...
    middleName = ""; // Make sure middName is empty.
    // Retrieve the Last Name.
    lastName = userInput.substring(userInput.indexOf(' ', 0)).trim();
}
/* Nope, must be three (or more) names. This demo is only going to 
   deal with either two or three names. If you like you can take it 
   further and place this sort of check in a loop to get all names 
   (a lot of people have more than three names).             */
else {
    /* Acquire the Middle Name (or initial). Notice how we've now
       added the length of the firstName ( plus 1) to the `fromIdex` 
       parameter of the indexOf() method?                     */
    middleName = userInput.substring(userInput.indexOf(' '), 
                             userInput.indexOf(' ', firstName.length()   1)).trim();

    /* Now acquire the Last Name. We're just summing the lengths of 
       the firstName and lastName and using it in the overloaded 
       version of the String#substring() method which require a 
       single argument which returns the string's substring from 
       the supplied index value to the end of String.         */
    lastName = userInput.substring(firstName.length()   middleName.length()   1).trim();
}
        
/* Display the acquired name components within the Console Window:
   Whitespacing between the First, Middle, and Last names is handled 
   through a Ternary Operator so as not to provide an addtional white-
   space if the Middle Name is empty (no middle name).        */
System.out.println(firstName   " "   (middleName.isEmpty() ? lastName : middleName   " "   lastName));

CodePudding user response:

I'm not going to include your boiler plater user I/O as you have that covered. The solution you want is regex:

//Last name is at index 0, First name at 1, and middle at 2
public static String[] getNames(String input) {
    String [] names = new String[3];
    Arrays.fill(names, "");

    Pattern pattern = Pattern.compile("\\b\\w (-\\w )?");
    Matcher matcher = pattern.matcher(input);
    int idx = 0;
    while(matcher.find() && idx < 3) {
        System.out.println(matcher.group());
        names[idx  ] = matcher.group();
    }

    return names;
} 
  • Related