我按名字和姓氏分隔字串。
我把最后一個詞等同于姓氏。我將余數等同于名字。
此字串可以為空或 null。我正在檢查空回傳。
但如果字串為空,我會收到以下錯誤。
或者只有名稱時出現錯誤。 例如; 字串測驗=“杰克”;
如何在不向代碼添加另一個“if else”控制元件的情況下在一行中執行此操作?
https://dotnetfiddle.net/7lr07G
[System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
at System.String.Substring(Int32 startIndex, Int32 length)
uj5u.com熱心網友回復:
試試這個:
//string test = "Jack ";
//string test = "Jack";
string test = "Jack Nelsson";
var firstname = string.Empty;
var lastname = string.Empty;
if (!string.IsNullOrEmpty(test))
{
var index = test.LastIndexOf(" ");
if (index < 0 || index >= test.Length - 1)
{
firstname = test.TrimEnd();
}
else
{
firstname = test.Substring(0, index);
lastname = test.Substring(index 1);
}
}
Console.WriteLine(firstname);
Console.WriteLine(lastname);
默認情況下,我們設定 string.Empty。如果 test 有一個字串,我們搜索最后一個空格并將其存盤在一個變數中以供以后使用。
如果未找到命名空間:將 firstname 設定為所有文本。如果在字串的末尾找到空格:將 firstname 設定為所有沒有結尾空格的文本。我們需要檢查這種情況,因為索引 1 的子字串在這種情況下會失敗。在其他情況下,在該點拆分字串。
uj5u.com熱心網友回復:
問題是test.LastIndexOf(" ")如果 . 中沒有空格則回傳 -1 test。看看MSDN - String.Substring
您可以使用String.Contains
var firstname = !string.IsNullOrEmpty(test) && test.Contains(" ")
? test.Substring(0, test.LastIndexOf(" "))
: string.IsNullOrEmpty(test) ? string.Empty : test;
var lastname = !string.IsNullOrEmpty(test) && test.Contains(" ")
? test.Split(' ').Last()
: string.Empty;
檢查是否有空格test。
我建議使用String.IsNullOrEmpty而不是test != null.
uj5u.com熱心網友回復:
我更喜歡IndexOf盡可能少地使用,因為我總是把自己與索引混淆。所以這里有不同的方法:
string firstname = "";
string lastname = "";
if (!string.IsNullOrEmpty(name))
{
var parts = name.Split(' ');
lastname = parts[parts.Length-1];
firstname = string.Join(" ", parts.Take(parts.Length-1));
}
它只是使用空格分割,然后將最后一部分作為姓氏,并將其他部分作為名字。
編輯
我剛剛看到了 Mighty Badaboom 的解決方案,并受到使用Last. 這是一個包含更少整數的版本:
string firstname = "";
string lastname = "";
if (!string.IsNullOrEmpty(name))
{
var parts = name.Split(' ');
lastname = parts.Last();
firstname = string.Join(" ", parts.SkipLast(1));
}
SkipLast 需要 .NET 標準 2.1。如果按照舊標準,您可以選擇:
firstname = string.Join(" ", parts.Reverse().Skip(1).Reverse());
uj5u.com熱心網友回復:
試試這個:
string test = "Jack Daniels";
var firstname = string.IsNullOrEmpty(test)
? string.Empty
: (test.Contains(" ") ? (test.Substring(0, test.LastIndexOf(" "))).Trim() : test);
var lastname = string.IsNullOrEmpty(test)
? string.Empty
: (test.Contains(" ") ? (test.Substring(test.LastIndexOf(" ")).Trim()) : string.Empty);
Console.WriteLine("firstname>>" firstname);
Console.WriteLine("lastname>>" lastname);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464853.html
