我有一個字符串中獲取某個字符的問題。例如,如果一個人名字中有兩個名字,我只想得到第一個名字。字符串修剪/子字符串C#
名:一月埃德森
輸出:一月
我一直在努力的Trim()
方法,但它只是刪除多餘的空格。 我還沒有試過Substring()
呢。
還有其他方法嗎?請幫忙。
謝謝!
我有一個字符串中獲取某個字符的問題。例如,如果一個人名字中有兩個名字,我只想得到第一個名字。字符串修剪/子字符串C#
名:一月埃德森
輸出:一月
我一直在努力的Trim()
方法,但它只是刪除多餘的空格。 我還沒有試過Substring()
呢。
還有其他方法嗎?請幫忙。
謝謝!
using System.Text.RegularExpressions;
string firstName = Regex.Match("Jan Edson", @"\w*").ToString();
您應該使用String.Split()
並按空格字符拆分。 這將導致既Jan
和
// The input string
const string name = "Jan Edson";
// Split by the spacebar
var nameParts = name.Split(' ');
// Will return 'Jan'
string firstPart = nameParts[0];
有幾種方法來實現這一目標。其中之一正在使用String.Split
string text = "Jan Edson";
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string[] words = text.Split(delimiterChars);
string firstName = "";
if (words.Count > 1)
firstName = word[0];
我其實更容易找到。謝謝你們的幫助! – edsonski