簡體   English   中英

C#字符串是否以空字符串結尾?

[英]Do C# strings end with empty string?

出於好奇只是一個簡短的問題。

string str = "string";
Console.WriteLine(str.EndsWith(string.Empty));                  //true
Console.WriteLine(str.LastIndexOf(string.Empty) == str.Length); //false
//of course string are indexed from 0, 
//just wrote if for fun to check whether empty string get some extra index
///somehow by a miracle:)

//finally

Console.WriteLine(str.LastIndexOf(string.Empty) 
               == str.LastIndexOf('g'));                        //true :)

EndsWith

確定此字符串實例的結尾是否與指定的字符串匹配。

所有字符串將在末尾匹配"" ...或字符串的任何其他部分。 為什么? 因為從概念上講,每個角色周圍都有空字符串。

"" + "abc" + "" == "abc" == "" + "a" + "" + "b" + "" + "c" + ""

更新:

關於你的最后一個例子 - LastIndexOf記錄了這個:

如果value為String.Empty,則返回值是此實例中的最后一個索引位置。


一個相關的問題是使用null作為字符串終止符 - 它發生在C和C ++中,而不是C#。

從MSDN - String Class (System)

在.NET Framework中,String對象可以包含嵌入的空字符,這些字符計為字符串長度的一部分。 但是,在某些語言(如C和C ++)中,空字符表示字符串的結尾; 它不被視為字符串的一部分,不計入字符串長度的一部分。

試試這個:

string str = "string";
Console.WriteLine(str.EndsWith(string.Empty));                  //true 
Console.WriteLine(str.LastIndexOf(string.Empty) == str.Length-1); // true
Console.ReadLine();

所以是的,正如Oded所說,他們總是匹配。

想一想: LastIndexOf對於一個空字符串來說是沒有意義的。 你可以說每個字符之間的字符串中的每個索引都存在空字符串。 因此, 文檔為應該返回的內容提供了明確的答案:

如果value為String.Empty ,則返回值是此實例中的最后一個索引位置。

至少在這種情況下,它返回一個實際索引。 如果它返回字符串的長度(表示索引“在結尾之后”,我相信這是你的觀點),它將返回一個名為LastIndexOf的方法的結果,該方法甚至不是索引。

這是另一種看待它的方式:如果我有這個:

Dim index As Integer = str.LastIndexOf("")

...那么我應該能夠做到這一點:

Dim substr As String = str.Substring(index, "".Length)

......並獲得""回來了。 果然,當LastIndexOf返回字符串中的最后一個索引時,它可以正常工作。 如果它返回字符串的 長度 ,我會得到一個 ArgumentOutOfRangeException 編輯 :好吧,看起來我錯了。 希望我的第一點足夠強大;)

這個問題及其答案中有更多信息。

特別是, "Indeed, the empty string logically occurs between every pair of characters."

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM