27.4k views
4 votes
Write a method named lastFirst that accepts a string as its parameter representing a person's first and last name. The method should return the person's last name followed by the first initial and a period. For example, the call lastFirst("Marla Singer") should return "Singer, M." . You may assume that the string passed consists of exactly two words separated by a single space.

User Kisna
by
4.8k points

1 Answer

2 votes

I'm going to assume this is Java, because you said "method" meaning it will be some sort of object oriented language, and Java's really common. Here would be the full program, but you can just take the method out isolated if you need it.

package lastname;

public class LastName {

public static void main(String[] args) {

// Example usage:

String name = LastName.lastName("Garrett Acord");

System.out.println(name);

// Output: Acord G.

}

public static String lastName(String fullName)

{

String[] splitName = fullName.split(" ");

return String.format("%s %s.", splitName[1], splitName[0].substring(0,1) );

}

}

User Cole Roberts
by
5.0k points