字符串问题。格式"最后一个"格式化#34; Last,First"扭曲

时间:2014-09-22 04:16:25

标签: vb.net string

我需要更改一个包含" First Last"格式化为"最后,第一个"格式。问题是,字符串可能像约翰史密斯"或者它可能是"先生。约翰史密斯"甚至"先生。约翰·A·史密斯"。如何消除" Mr。"部分和中间名称/初始部分,然后使它成为"史密斯,约翰"?我讨厌字符串btw ...我预见很多修剪(右),修剪(左)废话......请让它更容易!

我的目标是通过姓氏的第一个字母从数据库字段NAME中选择记录。字段NAME包含名称,如" John Smith" "先生。 Roger A. Smith" "先生。琼斯"我只需要一个能够返回史密斯而不是琼斯的搜索功能。

2 个答案:

答案 0 :(得分:1)

这是否符合您的要求?

Dim samples As String() = {
    "John Smith",
    "John A. Smith",
    "Mr. John Smith",
    "Mr. John A. Smith",
    "Jean-Claude Van Damme"
}

Dim regex As New Regex("(?:(?:mr\.|miss|mrs|ms)\s+)?(\S+).*(?<=\s)(\S+)$", RegexOptions.IgnoreCase)

For Each sample In samples
    Dim converted As String = regex.Replace(sample, "$2, $1")
    Console.WriteLine("{0} => {1}", sample, converted)
Next

结果:

John Smith => Smith, John
John A. Smith => Smith, John
Mr. John Smith => Smith, John
Mr. John A. Smith => Smith, John
Jean-Claude Van Damme => Damme, Jean-Claude

.Net Fiddle

答案 1 :(得分:-1)

我对vb.net并没有太多帮助,但是这段代码应该在修改后使用任何语言使用正确的函数名称

#include <string>

using namespace std;

int main()
{
    string name;

    unsigned int startIndex = 0;
    for(unsigned int i = name.length() - 1; name[i] != ' '; --i)
    {
        startIndex = i;
    }

    unsigned int LengthOfName = name.length();
    string sirName = name.substr(startIndex, LengthOfName);

    startIndex = 0;
    if(name[0] == 'm' || name[0] == 'M')
    {
        for(unsigned int i = 0; name[i] != ' '; ++i)
        {
            startIndex = i + 1;
        }
    }

    for(unsigned int i = startIndex; name[i] != ' '; ++i)
    {
        LengthOfName = i - startIndex;
    }

    string firstName = name.substr(startIndex, LengthOfName);

    name = sirName + ' ' + firstName;

    return 0;
 }

- 用c ++编写的代码