Get Initials and Full Last Name from a String Containing Names

Get initials and full last name from a string containing names

It wouldn't be possible without calling multiple replace() methods. The steps in provided solution is as following:

  • Remove all dots in abbreviated names
  • Substitute lastname with firstname
  • Replace lastnames with their beginning letter
  • Remove unwanted characters

Demo:

var s = `Guilcher, G.M., Harvey, M. & Hand, J.P.Ri Liesner, Peter Tom Collins, Michael RichardsManco-Johnson M, Santagostino E, Ljung R.`
// Remove all dots in abbreviated namesvar b = s.replace(/\b([A-Z])\./g, '$1')// Substitute first names and lastnames.replace(/([A-Z][\w-]+(?: +[A-Z][\w-]+)*) +([A-Z][\w-]+)\b/g, ($0, $1, $2) => { // Replace full lastnames with their first letter return $2 + " " + $1.replace(/\b([A-Z])\w+ */g, '$1');})// Remove unwanted preceding / following commas and ampersands .replace(/(,) +([A-Z]+)\b *[,&]?/g, ' $2$1');
console.log(b);

How to return the last name to the front and then follow by the initial of the first name using Python?

Since you don't want to use split you have to do the splitting manually. Find the space character and take everything after it as the last name.

def lastF(name):
index = name.index(' ')
last_name = name[index+1:]
first_character = name[0]
return f'{last_name}, {first_character}'

print(lastF('John Locke'))

The result is Locke, J.


The f-string in return f'{last_name}, {first_character}' prevents ugly string concatenation as in return last_name + ', ' + first_character.

You could even compress everything in one line:

def lastF(name):
return f'{name[name.index(" ")+1:]}, {name[0]}'

Convert full name input to last name + initials

As you do not use a dictionary in your code, I just provide a solution without dict.

name = input("Name: ").split()
print(f"{name.pop()}, {''.join(n[0] + '.' for n in name)}")

name.pop() gets the last name in list, n[0] + '.' gets the initials for the remaining names and adds a dot after them, then we use join() to combine these initials.

Test run:

Name: Pat Silly Doe
Doe, P.S.
Name: Julia Clark
Clark, J.

Using PHP to get initials of names with 4 letters of last name

Just use string functions. These work for the types of names you show. These obviously won't for John Paul Jones or Juan Carlos De Jesus etc. depending on what you want for them:

$initials = implode('/', array_map(function ($name) { 
return $name[0] . substr(trim(strstr($name, ' ')), 0, 4);
}, $names));
  • $name[0] is the first character
  • strstr return the space and everything after the space, trim the space
  • substr return the last 4 characters

Optionally, explode on the space:

$initials = implode('/', array_map(function ($name) { 
$parts = explode(' ', $name);
return $parts[0][0] . substr($parts[1], 0, 4);
}, $names));

For the preg_match:

$initials = implode('/', array_map(function ($name) { 
preg_match('/([^ ]) ([^ ]{4})/', $name, $matches);
return $matches[1].$matches[2];
}, $names));
  • ([^ ]) capture not a space
  • match a space
  • ([^ ]{4}) capture not a space 4 times

How do I get the first and last initial/character from a name string

You can use this regex to capture the first letter of first name in group1 and first letter of lastname in group2 and replace whole match with $1$2 to get the desired string.

^\s*([a-zA-Z]).*\s+([a-zA-Z])\S+$

Explanation:

  • ^ - Start of string
  • \s* - Matches optional whitespace(s)
  • ([a-zA-Z]) - Matches the first letter of firstname and captures it in group1
  • .*\s+ - Here .* matches any text greedily and \s+ ensures it matches the last whitespace just before last name
  • ([a-zA-Z]) - This captures the first letter of lastname and captures it in group2
  • \S+$ - Matches remaining part of lastname and end of input

Regex Demo

Java code,

String s = "A A BCD EFG";
System.out.println(s.replaceAll("^\\s*([a-zA-Z]).*\\s+([a-zA-Z])\\S+$", "$1$2"));

Prints,

AE

Edit: To convert/ensure the replaced text to upper case, in case the name is in lower case letters, in PCRE based regex you can use \U just before the replacement as \U$1$2 but as this post is in Java, it won't work that way and hence you can use .toUpperCase()

Demo for ensuring the replaced text is in upper case

Java code for same would be to use .toUpperCase()

String s = "a A BCD eFG";
System.out.println(s.replaceAll("^\\s*([a-zA-Z]).*\\s+([a-zA-Z])\\S+$", "$1$2").toUpperCase());

Prints in upper case despite the input string in lower case,

AE

How to print the first name and initials of a full name

  1. In order to get the first name, you can get the substring from index 0 till the first whitespace (i.e. fullName.indexOf(' '))
  2. In order to get the initials, you can get the first char of the string + the first char after the last whitespace (i.e. fullName.lastIndexOf(' ')).

Demo:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();

System.out.print("Greetings, " + getFirstName(fullName) + ", your initials are " + getInitials(fullName));
}

public static String getFirstName(String fullName) {
return fullName.substring(0, fullName.indexOf(' '));
}

public static String getInitials(String fullName) {
int idxLastWhitespace = fullName.lastIndexOf(' ');
return fullName.substring(0, 1) + fullName.substring(idxLastWhitespace + 1, idxLastWhitespace + 2);
}
}

A sample run:

Enter full name: Arvind Kumar Avinash
Greetings, Arvind, your initials are AA

C# Get Initials of DisplayName

Simple and easy to understand code and handles names which contain first, middle and last name such as "John Smith William".

Test at: https://dotnetfiddle.net/kmaXXE

 Console.WriteLine(GetInitials("John Smith"));  // JS
Console.WriteLine(GetInitials("Smith, John")); // SJ
Console.WriteLine(GetInitials("John")); // J
Console.WriteLine(GetInitials("Smith")); // S

Console.WriteLine(GetInitials("John Smith William")); // JSW
Console.WriteLine(GetInitials("John H Doe")); // JHD


static string GetInitials(string name)
{
// StringSplitOptions.RemoveEmptyEntries excludes empty spaces returned by the Split method

string[] nameSplit = name.Split(new string[] { "," , " "}, StringSplitOptions.RemoveEmptyEntries);

string initials = "";

foreach (string item in nameSplit)
{
initials += item.Substring(0, 1).ToUpper();
}

return initials;
}


Related Topics



Leave a reply



Submit