开发者

left string function in C#

开发者 https://www.devze.com 2023-01-14 00:39 出处:网络
What\'s the best way to return the first word of a string in C#? Basically if the string is \"hello world\", I need to get \"hello\".

What's the best way to return the first word of a string in C#?

Basically if the string is "hello world", I need to get "hello".

T开发者_开发知识库hanks


You can try:

string s = "Hello World";
string firstWord = s.Split(' ').First();

Ohad Schneider's comment is right, so you can simply ask for the First() element as there will always be at least one element.

For further info on whether to use First() or FirstOrDefault() you can learn more here


You can use a combination of Substring and IndexOf.

var s = "Hello World";
var firstWord = s.Substring(0,s.IndexOf(" "));

However, this will not give the expected word if the input string only has one word, so a special case is needed.

var s = "Hello";
var firstWord = s.IndexOf(" ") > -1 
                  ? s.Substring(0,s.IndexOf(" "))
                  : s;


One way is to look for a space in the string, and use the position of the space to get the first word:

int index = s.IndexOf(' ');
if (index != -1) {
  s = s.Substring(0, index);
}

Another way is to use a regular expression to look for a word boundary:

s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;


The answer of Jamiec is the most efficient if you want to split only on spaces. But, just for the sake of variety, here's another version:

var  FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0];

As a bonus this will also recognize all kinds of exotic whitespace characters and will ignore multiple consecutive whitespace characters (in effect it will trim the leading/trailing whitespace from the result).

Note that it will count symbols as letters too, so if your string is Hello, world!, it will return Hello,. If you don't need that, then pass an array of delimiter characters in the first parameter.

But if you want it to be 100% foolproof in every language of the world, then it's going to get tough...


Shamelessly stolen from the msdn site (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];
}


Handles the various different whitespace characters, empty string and string of single word.

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();
}


Instead of doing Split for all the string, Limit your Split to count of 2. Use the overload which takes count as parameter as well. Use String.Split Method (Char[], Int32)

string str = "hello world";
string firstWord = str.Split(new[]{' '} , 2).First();

Split will always return an array with at least one element so either .[0] or First is enough.


I used this function in my code. It provides an option to either uppercase the first word or every single word.

        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;
        }
    }


string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Length >0){
 string first = split[0];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消