Search code examples
stringaxaptax++dynamics-365-operations

split full name to first ,middle and last in x++ d365fo


i want to split full name to first ,middle and last in x++ d365fo

str fullName = _contracts.fullName();

// Replace any non-ASCII whitespace characters with regular spaces
fullName = strReplace(fullName, '\u00A0', ' '); // Replace non-breaking spaces with regular spaces
fullName = strReplace(fullName, '\t', ' ');    // Replace tabs with regular spaces

// Trim any leading or trailing whitespace characters from the full name
fullName = strTrim(fullName);


// Split full name into first, middle, and last name
str firstName;
str middleName;
str lastName;

// Find the last space character to split the full name into first and last name
int lastSpace = strFind(fullName, " ", strLen(fullName), -1);
if (lastSpace >= 0)
{
    lastName = subStr(fullName, lastSpace + 1, strLen(fullName));

    // Find the first space character to split the full name into first and middle name
    int firstSpace = strFind(fullName, " ", 0, 1);
    if (firstSpace >= 0 && firstSpace < lastSpace)
    {
        firstName = subStr(fullName, 1, firstSpace - 1);
        middleName = subStr(fullName, firstSpace + 1, lastSpace - firstSpace - 1);
    }
    else
    {
        // No space found before last space, assume the full name is just a first name and last name
        firstName = "";
        middleName = "";
    }
}
else
{
    // No space found, assume the full name is just a first name
    firstName = fullName;
}

this is how the object passes "fullName":"mh ali hasan"

i got lastname ="mh ali hasan" sounds like he doesn't recognize the spaces


Solution

  • Don't reinvent the wheel if you don't have to. Modify as needed to handle special characters or other circumstances.

    [firstName, middleName, lastName] = DirPerson::splitNameParts("John Michael Smith");