简体   繁体   English

C#:如何获取字符串的第一个字符?

[英]C#: how to get first char of a string?

可以通过执行以下操作来检索字符串的第一个char吗?

MyString.ToCharArray[0]

Just MyString[0] .只是MyString[0] This uses the String.Chars indexer.这使用String.Chars索引器。

Mystring[0]应该就够了

试试这个,

string s1="good"; string s=s1.Substring(0,1);

You can use LINQ您可以使用 LINQ

char c = mystring.FirstOrDefault()

It will be equal to '\\0' if the string is empty.如果字符串为空,它将等于'\\0'

The difference between MyString[0] and MyString.ToCharArray()[0] is that the former treats the string as a read-only array, while ToCharArray() creates a new array. MyString[0]MyString.ToCharArray()[0]的区别在于前者将字符串视为只读数组,而ToCharArray()创建一个新数组。 The former will be quicker (along with easier) for almost anything where it will work, but ToCharArray can be necessary if you have a method that needs to accept an array, or if you want to change the array.对于几乎可以工作的任何地方,前者会更快(以及更容易),但是如果您有一个需要接受数组的方法,或者如果您想更改数组,则ToCharArray可能是必要的。

If the string isn't known to be non-null and non-empty you could do:如果字符串不知道是非空和非空,你可以这样做:

string.IsNullOrEmpty(MyString) ? (char?)null : MyString[0]

which returns a char?哪个返回一个char? of either null or the first character in the string, as appropriate.为空或字符串中的第一个字符,视情况而定。

或者你可以这样做:

MyString[0];

Just another approach:只是另一种方法:

string mystr = "hello";
MessageBox.show(mystr.Substring(0, 1));

I think you are looking for this MyString.ToCharArray()[0]我想你正在寻找这个MyString.ToCharArray()[0]

:) :)

But you can use MyString[0] too.但是你也可以使用MyString[0]

Starting with C# 8.0+ we can use the range indexer syntax.从 C# 8.0+ 开始,我们可以使用范围索引器语法。

The following code:以下代码:

var name = "Dotnet".Substring(0, 1)

can be written using range syntax:可以使用范围语法编写:

var name = "Dotnet"[..1]

Try it out in Dotnet fiddle在 Dotnet fiddle 中尝试一下

See official docs for more examples 有关更多示例,请参阅官方文档

The above code will throw if the input string is less than range index.如果输入字符串小于范围索引,上面的代码将抛出。 This LINQ will prevent that problem:此 LINQ 将防止该问题:

var name = "Dotnet".Take(1).ToArray()

Try it out in Dotnet fiddle在 Dotnet fiddle 中尝试一下

以下从字符串中获取第一个字符的示例可能对某人有所帮助

string anyNameForString = "" + stringVariableName[0];

In C# 8 you can use ranges.在 C# 8 中,您可以使用范围。

myString[0..Math.Min(myString.Length, 1)]

Add a ?添加一个? after myString to handle null strings.myString之后处理null字符串。

MyString.Remove(1, 2); MyString.Remove(1, 2); also works也有效

Answer to your question is NO.你的问题的答案是否定的。

Correct is MyString[position of character].正确的是 MyString[字符位置]。 For your case MyString[0], 0 is the FIRST character of any string.对于您的情况 MyString[0],0 是任何字符串的第一个字符。

A character value is designated with ' (single quote), like this x character value is written as 'x'.一个字符值用 '(单引号)指定,就像这个 x 字符值被写成 'x'。

A string value is designated with " ( double quote), like this x string value is written as "x".字符串值用“(双引号)指定,就像这个 x 字符串值写为“x”。

So Substring() method is also does not return a character, Substring() method returns a string!!!所以 Substring() 方法也是不返回字符,Substring() 方法返回一个字符串!!!

A string is an array of characters, and last character must be '\\0' (null) character.字符串是一个字符数组,最后一个字符必须是'\\0'(空)字符。 Thats the difference between character array and string ( which is an array of characters with last character as "end of string marker" '\\0' null.这就是字符数组和字符串(它是一个字符数组,最后一个字符为“字符串结束标记”'\\0' null。

And also notice that 'x' IS NOT EQUAL to "x".还要注意“x”不等于“x”。 Because "x" is actually 'x'+'\\0'.因为“x”实际上是'x'+'\\0'。

Maybe this will help.也许这会有所帮助。 I'm using txtModel_Leave event then create method to detect the first char in main textbox.我正在使用txtModel_Leave事件然后创建方法来检测主文本框中的第一个字符。

private void txtMain_Leave(object sender, EventArgs e)
{
    detectFirstChar();
}

private void detectFirstChar() 
{
    string mystr = txtModel.Text;

    if (String.IsNullOrEmpty(txtModel.Text))
    {
        txtAwalan.Text = "";
    }
    else if (mystr.Substring(0, 1) == "F")
    {
        txtKategori.Text = "Finishing";               
    }
    else if((mystr.Substring(0, 1) == "H"))
    {
        txtKategori.Text = "Half";
    }
    else
    {
        txtKategori.Text = "NONE";
    }
}

getting a char from a string may depend on the enconding (string default is UTF-16)从字符串中获取字符可能取决于编码(字符串默认为 UTF-16)

https://stackoverflow.com/a/32141891 https://stackoverflow.com/a/32141891

string str = new String(new char[] { '\uD800', '\uDC00', 'z' });
string first = str.Substring(0, char.IsHighSurrogate(str[0]) ? 2 : 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM