在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
You want to split strings on different characters with single character or string delimiters. For example, split a string that contains "\r\n" sequences, which are Windows newlines. Through these examples, we learn ways to use the Split method on the string type in the C# programming language. Use the Split method to separate parts from a string. Using SplitTo begin, we look at the basic Split method overload. You already know the general way to do this, but it is good to see the basic syntax before we move on. This example splits on a single character. === Example program for splitting on spaces (C#) === Description. The input string, which contains four words, is split on spaces and the foreach loop then displays each word. The result value from Split is a string[] array. Multiple charactersHere we use either the Regex method or the C# new array syntax. Note that a new char array is created in the following usages. There is an overloaded method with that signature if you need StringSplitOptions, which is used to remove empty strings. === Program that splits on lines with Regex (C#) === StringSplitOptionsWhile the Regex type methods can be used to Split strings effectively, the string type Split method is faster in many cases. The Regex Split method is static; the string Split method is instance-based. The next example shows how you can specify an array as the first parameter to string Split. === Program that splits on multiple characters (C#) === Overview. One useful overload of Split receives char[] arrays. The string Split method can receive a character array as the first parameter. Each char in the array designates a new block. Using string arrays. Another overload of Split receives string[] arrays. This means string array can also be passed to the Split method. The new string[] array is created inline with the Split call. Explanation of StringSplitOptions. The RemoveEmptyEntries enum is specified. When two delimiters are adjacent, we end up with an empty result. We can use this as the second parameter to avoid this. The following screenshot shows the Visual Studio debugger. See StringSplitOptions Enumeration.
Separating wordsHere we see how you can separate words with Split. Usually, the best way to separate words is to use a Regex that specifies non-word chars. This example separates words in a string based on non-word characters. It eliminates punctuation and whitespace from the return array. === Program that separates on non-word pattern (C#) === Word splitting example. Here you can separate parts of your input string based on any character set or range with Regex. Overall, this provides more power than the string Split methods. See Regex.Split Method Examples. Splitting text filesHere you have a text file containing comma-delimited lines of values. This is called a CSV file, and it is easily dealt with in the C# language. We use the File.ReadAllLines method here, but you may want StreamReader instead. This code reads in both of those lines, parses them, and displays the values of each line after the line number. The final comment shows how the file was parsed into the strings. === Contents of input file (TextFile1.txt) === Splitting directory pathsHere we see how you can Split the segments in a Windows local directory into separate strings. Note that directory paths are complex and this may not handle all cases correctly. It is also platform-specific, and you could use System.IO.Path. DirectorySeparatorChar for more flexibility. === Program that splits Windows directories (C#) === Internal logicThe logic internal to the .NET framework for Split is implemented in managed code. The methods call into the overload with three parameters. The parameters are next checked for validity. Finally, it uses unsafe code to create the separator list, and then a for loop combined with Substring to return the array. BenchmarksI tested a long string and a short string, having 40 and 1200 chars. String splitting speed varies on the type of strings. The length of the blocks, number of delimiters, and total size of the string factor into performance. The Regex.Split option generally performed the worst. I felt that the second or third methods would be the best, after observing performance problems with regular expressions in other situations. === Strings used in test (C#) === Longer strings: 1200 chars. The benchmark for the methods on the long strings is more even. It may be that for very long strings, such as entire files, the Regex method is equivalent or even faster. For short strings, Regex is slowest, but for long strings it is very fast. === Benchmark of Split on long strings === Short strings: 40 chars. This shows the three methods compared to each other on short strings. Method 1 is the Regex method, and it is by far the slowest on the short strings. This may be because of the compilation time. Smaller is better. This article was last updated for .NET 3.5 SP1. Performance recommendation. For programs that use shorter strings, the methods that split based on arrays are faster and simpler, and they will avoid Regex compilation. For somewhat longer strings or files that contain more lines, Regex is appropriate. Also, I show some Split improvements that can improve your program. Escaped charactersHere we note that you can use Replace on your string input to substitute special characters in for any escaped characters. This can solve lots of problems on parsing computer-generated code or data. See Split Method and Escape Characters. Delimiter arraysIn this section, we focus on how you can specify delimiters to the Split method in the C# language. My further research into Split and its performance shows that it is worthwhile to declare your char[] array you are splitting on as a local instance to reduce memory pressure and improve runtime performance. There is another example of delimiter array allocation on this site. === Slow version, before (C#) === Interpretation. We see that storing the array of delimiters separately is good. My measurements show the above code is less than 10% faster when the array is stored outside the loop. ExplodeIn this part, we discuss the explode function from the PHP environment. The .NET Framework has no explode method exactly like PHP explode, but you can gain the functionality quite easily with Split, for the most part. You can replace explode with the Split method that receives a string[] array. Explode allows you to split strings based on a fixed size. The new article on this topic implements the logic in the C# language directly. See Explode String Extension Method. SummaryIn this tutorial, we saw several examples and two benchmarks of the Split method in the C# programming language. You can use Split to divide or separate your strings while keeping your code as simple as possible. Sometimes, using IndexOf and Substring together to parse your strings can be more precise and less error-prone. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论