string s = "Hello World"; string firstWord = s.Split(' ').First();
16
0
9 Answer
39
あなたが試すことができます:
string s = "Hello World"; string firstWord = s.Split(' ').First();
Ohad Schneider’sコメントは正しいので、常に少なくとも1つの要素が存在するため、 `First()`要素を単に要求できます。
`First()`または `FirstOrDefault()`を使用するかどうかの詳細については、https://stackoverflow.com/questions/1024559/when-to-use-first-and-when-to-use-をご覧ください。 firstordefault-with-linq [ここ]
20
「Substring」と「IndexOf」の組み合わせを使用できます。
var s = "Hello World"; var firstWord = s.Substring(0,s.IndexOf(" "));
ただし、入力文字列に含まれる単語が1つだけの場合、期待される単語は得られないため、特別な場合が必要です。
var s = "Hello"; var firstWord = s.IndexOf(" ") > -1 ? s.Substring(0,s.IndexOf(" ")) : s;
8
1つの方法は、文字列内のスペースを探し、スペースの位置を使用して最初の単語を取得することです。
int index = s.IndexOf(' '); if (index != -1) { s = s.Substring(0, index); }
別の方法は、正規表現を使用して単語の境界を探すことです。
s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;
3
Jamiecの回答は、スペースのみで分割する場合に最も効率的です。 しかし、単に多様性のために、別のバージョンがあります:
var FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0];
ボーナスとして、これはhttp://msdn.microsoft.com/en-us/library/t809ektx.aspx [すべての種類のエキゾチックな空白文字]も認識し、複数の連続する空白文字を無視します(実際には、先頭/結果の末尾の空白)。
シンボルも文字としてカウントされるため、文字列が「Hello、world!」の場合は「Hello、」を返します。 必要ない場合は、最初のパラメーターに区切り文字の配列を渡します。
しかし、世界のすべての言語で100%確実に使用したい場合は、難しくなります…
2
msdnサイト(http://msdn.microsoft.com/en-us/library/b873y76a.aspx)から恥知らずに盗まれた
string words = "This is a list of words, with: a bit of punctuation" + "\tand a tab character."; string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' }); if( split.Length > 0 ) { return split[0]; }
1
さまざまな異なる空白文字、空の文字列、および単一単語の文字列を処理します。
private static string FirstWord(string text) { if (text == null) throw new ArgumentNullException("text"); var builder = new StringBuilder(); for (int index = 0; index < text.Length; index += 1) { char ch = text[index]; if (Char.IsWhiteSpace(ch)) break; builder.Append(ch); } return builder.ToString(); }
1
すべての文字列に対して「Split」を実行する代わりに、* Splitを2のカウントに制限します*。 カウントもパラメーターとして受け取るオーバーロードを使用します。 String.Split Method(Char [、Int32)]を使用します
string str = "hello world"; string firstWord = str.Split(new[]{' '} , 2).First();
Split`は常に少なくとも1つの要素を持つ配列を返すため、
。[0] または
First`で十分です。
0
string words = "hello world"; string [] split = words.Split(new Char [] {' '}); if(split.Length >0){ string first = split[0]; }
0
この関数をコードで使用しました。 最初の単語を大文字にするか、すべての単語を入力するかを選択できます。
public static string FirstCharToUpper(string text, bool firstWordOnly = true) { try { if (string.IsNullOrEmpty(text)) { return text; } else { if (firstWordOnly) { string[] words = text.Split(' '); string firstWord = words.First(); firstWord = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstWord.ToLower()); words[0] = firstWord; return string.Join(" ", words); } else { return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower()); } } } catch (Exception ex) { Log.Exc(ex); return text; } }