本文介绍了如何从字符串中获取姓氏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的clientName如下:

1)MOHD ASHRAF

2)PRAMODE KUMAR MEHROTRA

3)SHUSHMA VERMA

4)KUMAR VIVEK MISHRA



i希望得到他/她的姓氏,如{ASHRAF,MEHROTRA,VERMA, MISHRA}

所以我会告诉我

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

推荐答案

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;
     }
}




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



如果你有一个名字列表,如果你想获得一个姓氏列表,那么首先创建 GetLastname 扩展方法,然后尝试这个:


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:

List<string> lastnames = names.Select(x => x.GetLastname());



有关扩展方法的更多信息: []



希望这有帮助。


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

Hope this helps.


string tempName = "Ashok Kumar Malhotra";
string surname = tempName.Substring(tempName.LastIndexOf(' ') + 1);


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


这篇关于如何从字符串中获取姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 19:58