Click here to Skip to main content
15,886,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
My clientName is following:
1)MOHD ASHRAF
2)PRAMODE KUMAR MEHROTRA
3)SHUSHMA VERMA
4)KUMAR VIVEK MISHRA

i want to get his/her last name like{ASHRAF, MEHROTRA,VERMA,MISHRA}
so i will get plz tell me
Posted

To get the last name, try this:
C#
public static class ExtensionMethods
{
     public static string GetLastname(this string name) // create this extension method
     {
          string[] parts = name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
          string lastname = parts[parts.Length - 1];
          return lastname;
     }
}

C#
string lastname = name.GetLastname(); // now, try this code to get the last name

If you've a list of names, and if you want to get a list of last names, then first create the GetLastname extension method, and then try this:
C#
List<string> lastnames = names.Select(x => x.GetLastname());

More about extension methods: Extension Methods (C# Programming Guide)[^]

Hope this helps.
 
Share this answer
 
v2
Comments
Zafar Sultan 20-Aug-13 5:31am    
+5 for reusable code.
Thomas Daniels 20-Aug-13 5:31am    
Thank you!
codeninja-C# 20-Aug-13 9:48am    
GOOD ONE:) +5
Thomas Daniels 20-Aug-13 10:50am    
Thank you!
fjdiewornncalwe 20-Aug-13 11:44am    
+5. Very nice.
Try this:
C#
string tempName = "Ashok Kumar Malhotra";
string surname = tempName.Substring(tempName.LastIndexOf(' ') + 1);
 
Share this answer
 
SQL server side query:
SQL
DECLARE @tmp TABLE (sName VARCHAR(300))

INSERT INTO @tmp (sName)
SELECT 'MOHD ASHRAF'
UNION ALL SELECT 'PRAMODE KUMAR MEHROTRA'
UNION ALL SELECT 'SHUSHMA VERMA'
UNION ALL SELECT 'KUMAR VIVEK MISHRA'

SELECT sName, SUBSTRING(sName,LEN(sName) - CHARINDEX(' ',REVERSE(sName)) + 2,LEN(sName)) AS LastName
FROM @tmp



Result:
MOHD ASHRAF		ASHRAF
PRAMODE KUMAR MEHROTRA	MEHROTRA
SHUSHMA VERMA		VERMA
KUMAR VIVEK MISHRA	MISHRA
 
Share this answer
 
You may split each string using the blank as separator and then take the last item of the resulting array, e.g.
C#
string fullname = "MOHD ASHRAF";
string [] names = fullname.Split(new char[] { ' ' });
string lastname = names[names.Length - 1];
 
Share this answer
 
Hi,

Hope it helps,

C#
string name = "MOHD ASHRAF";
string lastName = name.Split().Last();


--SJ
 
Share this answer
 
C#
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "KUMAR VIVEK MISHRA";
          string [] nameArray = name.Split(new char[0]);
          string lastName = nameArray[nameArray.Length - 1];
          Console.WriteLine("Last name is {0}", lastName);
          Console.ReadKey();

        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900