[英]separate first middle last name C#
目標:在用戶輸入姓名時解析姓名,並顯示帶有第一個中間名和姓氏的消息框。 現在它只在你輸入三個名字時才有效,如果你嘗試兩個它會崩潰,我確定這是我的數組的原因,但我不確定我錯在哪里。 超級新手,我自己學習,所以任何幫助將不勝感激!!
用戶看到的 PS GUI 只是一個輸入塊,供他們將他們的名字輸入一行,每個單詞之間有間距。
private void btnParseName_Click(object sender, System.EventArgs e)
{
string fullName = txtFullName.Text;
fullName = fullName.Trim();
string[] names = fullName.Split(' ');
string firstName = "";
string firstLetter = "";
string otherFirstLetters = "";
if (names[0].Length > 0)
{
firstName = names[0];
firstLetter = firstName.Substring(0, 1).ToUpper();
otherFirstLetters = firstName.Substring(1).ToLower();
}
string secondName = "";
string secondFirstLetter = "";
string secondOtherLetters = "";
if (names[1].Length > 0)
{
secondName = names[1];
secondFirstLetter = secondName.Substring(0, 1).ToUpper();
secondOtherLetters = secondName.Substring(0).ToLower();
}
string thirdName = "";
string thirdFirstLetter = "";
string thirdOtherLetters = "";
if (names[2].Length > 0)
{
thirdName = names[2];
thirdFirstLetter = thirdName.Substring(0, 1).ToUpper();
thirdOtherLetters = thirdName.Substring(0).ToLower();
}
MessageBox.Show(
"First Name: " + firstLetter + otherFirstLetters + "\n\n" +
"Middle Name: " + secondFirstLetter + secondOtherLetters + "\n\n" +
"Last Name: " + thirdFirstLetter + thirdOtherLetters);
以下是如何執行此操作的工作示例:
public class FullName
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public FullName()
{
}
public FullName(string fullName)
{
var nameParts = fullName.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (nameParts == null)
{
return;
}
if (nameParts.Length > 0)
{
FirstName = nameParts[0];
}
if (nameParts.Length > 1)
{
MiddleName = nameParts[1];
}
if (nameParts.Length > 2)
{
LastName = nameParts[2];
}
}
public override string ToString()
{
return $"{FirstName} {MiddleName} {LastName}".TrimEnd();
}
}
用法示例:
class Program
{
static void Main(string[] args)
{
var fullName = new FullName("first middle last");
Console.WriteLine(fullName);
Console.ReadLine();
}
}
您需要檢查並處理第二個名稱為空。 初始化字符串將防止崩潰,然后檢查輸入。
string secondName = "";
string secondFirstLetter = "";
string secondOtherLetters = "";
if(names.Length > 2)
{
secondName = names[1];
secondFirstLetter = secondName.Substring(0, 1).ToUpper();
secondOtherLetters = secondName.Substring(0).ToLower();
}
實際上,值得初始化所有變量或管理用戶輸入驗證。
如另一個答案所述,只有在存在第三個名稱時才需要指定中間名。
下面的方法使用Dictionary.TryGetValue
方法和C#7功能out
參數。
var textInfo = System.Globalization.CultureInfo.CurrentCulture.TextInfo;
var names = fullName.Split(' ')
.Where(name => string.IsNullOrWhiteSpace(name) == false)
.Select(textInfo.ToTitleCase)
.Select((Name, Index) => new { Name, Index })
.ToDictionary(item => item.Index, item => item.Name);
names.TryGetValue(0, out string firstName);
names.TryGetValue(1, out string middleName);
if (names.TryGetValue(2, out string lastName) == false)
{
lastName = middleName;
middleName = null;
}
// Display result
var result = new StringBuilder();
result.AppendLine("First name: ${firstName}");
result.AppendLine("Middle name: ${middleName}");
result.AppendLine("Last name: ${lastName}");
MessageBox.Show(result.ToString());
我知道你的問題已得到解答,你可以通過很多方式來處理這個問題,但這是我的建議,並在此過程中給出了一些解釋:
private void button1_Click(object sender, EventArgs e)
{
string fullName = "Jean Claude Van Dam";
fullName = fullName.Trim();
// So we split it down into tokens, using " " as the delimiter
string[] names = fullName.Split(' ');
string strFormattedMessage = "";
// How many tokens?
int iNumTokens = names.Length;
// Iterate tokens
for(int iToken = 0; iToken < iNumTokens; iToken++)
{
// We know the token will be at least one letter
strFormattedMessage += Char.ToUpper(names[iToken][0]);
// We can't assume there is more letters (they might have used an initial)
if(names[iToken].Length > 1)
{
// Add them (make it lowercase)
strFormattedMessage += names[iToken].Substring(1).ToLower();
// Don't need to add "\n\n" for the last token
if(iToken < iNumTokens-1)
strFormattedMessage += "\n\n";
}
// Note, this does not take in to account names with hyphens or names like McDonald. They would need further examination.
}
if(strFormattedMessage != "")
{
MessageBox.Show(strFormattedMessage);
}
}
這個例子避免了所有的變量。 它利用了運算符[] 。
希望這對你有幫助...... :)
public static string getMiddleName(string fullName)
{
var names = fullName.Split(' ');
string firstName = names[0];
string middleName = "";// names[1];
var index = 0;
foreach (var item in names)
{
if (index > 0 && names.Length -1 < index)
{
middleName += item + " ";
}
index++;
}
return middleName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.