Answer :
Answer:
name = input(" Enter your Name:")
br = name.split()
def split(word):
return list(word)
word = br[1]
print(br[2],", ",br[0]," ",word[0])
Explanation:
The Programming Language used is python.
The function used is called a split function, it allows the splitting of a string into a list of words and is the best method to accomplish this particular task.
Line 1:
name = input(" Enter your Name:")
initializes the string and prompts the person to input a name
Line 2:
br = name.split()
uses split() to break the string up into a list of words. with each slot having its unique identifier (index number) starting from 0.
Line 3, 4, 5 :
def split(word):
return list(word)
word = br[1]
- if the input as in your example is "Pat Silly Doe" what happens is that "Pat Silly Doe" is broken up into a list.
-we now have [Pat, Silly, Doe] and each of the elements in the list have their unique index.
Pat-0
Silly-1
Doe-2
Silly is split into individual characters [s,i,l,l,y]
Line 6:
print(br[2]," ",br[0]," ",word[0])
This prints out the names in the new format of:
br[2] --> Doe
br[0] --> Pat
word[0] --> s
Doe, Pat S
Answer:
The code is given below in Java with appropriate comments
Explanation:
//declaring the imports
import java.util.Scanner;
//class FormatName
public class FormatName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//inputing the names
System.out.print("Enter your name (first middle last): ");
String fullName = scanner.nextLine();
String[] names = fullName.split("\\s+");
//applying the formatting
if (names.length == 2) {
System.out.println("Formatted Name: " + names[1] + ", " + names[0]);
} else if (names.length == 3) {
System.out.println("Formatted Name: " + names[2] + ", " + names[0] + " " + names[1].charAt(0) + ".");
} else {
System.out.println("The input does not have correct form");
}
}
}