1
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".

talex
  • 17,973
  • 3
  • 29
  • 66
  • 1
    To determine that there is only one space you need to check if the first space and the last space are at the same position: `if(firstSpace == secondSpace)`. Because if the first space is also the last there is only one space. – OH GOD SPIDERS Oct 06 '22 at 15:21
  • To handle multiple spaces in succession you could first replace multiple spaces with a single one: [Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces](https://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-lead) – OH GOD SPIDERS Oct 06 '22 at 15:25
  • @OHGODSPIDERS Hi thanks for the answer, my primary question was what if there are multiple spaces as "Phone. apple" this still satisfies for firstSpace, secondSpace – Johnny Song Oct 06 '22 at 15:35
  • Wouldn't it be easier to enter each name part separately? – g00se Oct 06 '22 at 16:28
  • @g00se that would solve this problem but I am not also allowed to have input separately either.... – Johnny Song Oct 06 '22 at 16:53
  • OK, then I'd probably start off with ```userInput = userInput.replaceAll("\\s+", "\\s");``` – g00se Oct 06 '22 at 16:58
  • @JohnnySong It will be helpful if you provide a few sample inputs and the expected outputs. – Arvind Kumar Avinash Oct 06 '22 at 17:19
  • @ArvindKumarAvinash If input is "Apple (empty Sapces) Iphone", then output should be "Iphone, A.", if input "Apple (empty Sapces) Samsung (empty Sapces) Phone", output is Phone, A.S. – Johnny Song Oct 07 '22 at 08:27
  • @JohnnySong - Alright. Let me see if I can help you with a solution. By the way, in your code (`System.out.println(lastName+ ", " + firstName.charAt(0));`), there is no dot (`.`) at the end. – Arvind Kumar Avinash Oct 07 '22 at 12:05
  • @ArvindKumarAvinash oh yeah it should be (System.out.println(lastName+ ", " + firstName.charAt(0)+ '.' ); thanks for the alert – Johnny Song Oct 07 '22 at 12:22

3 Answers3

1

Use the overloaded indexOf i.e. String::indexOf(String str, int fromIndex) to find the second space and accordingly adjust other parts of your code as shown below:

import java.util.Scanner;

public class Main {
    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.indexOf( ' ', firstSpace + 1);
        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(firstSpace + 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();
            System.out.println(middleName);
            lastName = userInput.substring(secondSpace + 1, userInput.length());
            System.out.println(lastName + ", " + firstName.charAt(0) + '.' + middleName.charAt(0) + '.');
        }
    }
}

A sample run:

Enter firstName middleName lastName separated by at least one blank, It may have more than one blank separating firstName middleName lastName
Apple Phone
Value of First:Apple     Second:-1
Phone, A.

Another sample run:

Enter firstName middleName lastName separated by at least one blank, It may have more than one blank separating firstName middleName lastName
Apple Samsung Phone
Value of First:Apple     Second:13
Samsung
Phone, A.S.
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Yes this is right in case of if there only one space between tokens, however, if there are more than one space, then it doesn't print correctly. Ex: Apple"multiple white spaces"Phone, then if(secondSpace<0) wouldn't be satisfied. I would like to solve for the case having multiple white spaces between tokens – Johnny Song Oct 07 '22 at 12:33
  • That's another problem and you can post another question about that. – Arvind Kumar Avinash Oct 07 '22 at 12:44
0

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));
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • Quick question, what does "[^ ]" mean? I think I saw this in C as Space character – Johnny Song Oct 07 '22 at 08:32
  • It's a Regular Expression. In the context that it's being used (within the `replaceAll()` method), it basically means: "replace everything within the string **except** whitespaces with `""` (nothing - remove it). When the method is done doing that then we can count the number of spaces that are in the string hence the `.length()` attached to get that count. – DevilsHnd - 退職した Oct 07 '22 at 08:49
  • The comments within the second version of the code explains this. – DevilsHnd - 退職した Oct 07 '22 at 08:55
0

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;
} 
Ryan
  • 1,762
  • 6
  • 11