Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
CSharp /
20180404astring slicingWarning! C#'s csharp> var s = "Fallout: New Vegas" csharp> s.Substring(0, 4) "Fall" // Seems good, right? csharp> s.Substring(4, 7) "out: Ne" // Ooops! What da hell?
Note that To simulate Python's string slicing, I have this solution: /// <summary> /// Get the string slice between the two indexes. /// Inclusive for start index, exclusive for end index. /// </summary> public static string Slice(this string s, int start, int end) { // based on https://www.dotnetperls.com/string-slice if (start < 0) // support negative indexing { start = s.Length + start; } if (end < 0) // support negative indexing { end = s.Length + end; } if (start > s.Length) // if the start value is too high { start = s.Length; } if (end > s.Length) // if the end value is too high { end = s.Length; } var len = end - start; // Calculate length if (len < 0) { len = 0; } return s.Substring(start, len); // Return Substring of length } For usage examples, here are some tests: [Fact] public void Slice_string() { const string s1 = "Fallout: New Vegas"; Assert.Equal("Fall", s1.Slice(0, 4)); Assert.Equal("out", s1.Slice(4, 7)); Assert.Equal("out: New Vega", s1.Slice(4, 17)); Assert.Equal("out: New Vegas", s1.Slice(4, 18)); Assert.Equal("out: New Vegas", s1.Slice(4, 19)); Assert.Equal("out: New Vegas", s1.Slice(4, 30)); Assert.Equal("gas", s1.Slice(-3, s1.Length)); Assert.Equal("Vegas", s1.Slice(-5, s1.Length)); Assert.Equal("Vega", s1.Slice(-5, -1)); Assert.Equal("", s1.Slice(100, 200)); const string s2 = "batman"; Assert.Equal("bat", s2.Slice(0, 3)); Assert.Equal("man", s2.Slice(3, s2.Length)); Assert.Equal("atm", s2.Slice(1, 4)); Assert.Equal("man", s2.Slice(-3, s2.Length)); } See the current version here. |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |