C#使用StreamReader读取文本后,如何去除冒号后的内容?
Hey there! Let's tackle this problem together. You want to extract the parts before each colon (:) from your text file using StreamReader, and mentioned you can't use the Split function. No worries—we can work around that with basic string manipulation methods like IndexOf and Substring, which are perfect for this scenario.
Step-by-Step Implementation
Here's a complete code example that reads your file line by line, extracts the desired names, and outputs them:
using System; using System.IO; class Program { static void Main() { // Replace with your actual file path string filePath = "your_text_file.txt"; // Use StreamReader to read the file line by line (auto-disposes resources) using (StreamReader reader = new StreamReader(filePath)) { string line; // Read each line until we reach the end of the file while ((line = reader.ReadLine()) != null) { ExtractNamesFromLine(line); } } } static void ExtractNamesFromLine(string line) { int currentPosition = 0; int lineLength = line.Length; while (currentPosition < lineLength) { // Find the next colon starting from our current position int colonIndex = line.IndexOf(':', currentPosition); if (colonIndex == -1) break; // No more colons to process in this line // Backtrack to find the start of the current name (stop at the previous space) int nameStartIndex = currentPosition; while (nameStartIndex > 0 && line[nameStartIndex - 1] != ' ') { nameStartIndex--; } // Extract the name and trim any accidental leading/trailing spaces string name = line.Substring(nameStartIndex, colonIndex - nameStartIndex).Trim(); Console.WriteLine(name); // Jump to the next item by finding the space after the colon int nextSpaceIndex = line.IndexOf(' ', colonIndex); currentPosition = nextSpaceIndex == -1 ? lineLength : nextSpaceIndex + 1; } } }
How It Works
- Reading the File: We use
StreamReaderinside ausingblock to make sure the file is properly closed after reading, and process each line individually. - Locating Colons:
IndexOfhelps us find exactly where each colon sits, marking the end of the name we want. - Extracting Names: We backtrack from the colon to find the start of the name (stopping at the nearest space), then use
Substringto grab the text between that start point and the colon.Trim()cleans up any stray spaces. - Moving to Next Entry: After processing one name, we jump to the next space after the colon to start on the next entry in the line.
Alternative: Using Regular Expressions (If You're Open to It)
If you don't mind using regex (which simplifies the code a lot), here's a shorter approach that still avoids Split:
using System; using System.IO; using System.Text.RegularExpressions; class Program { static void Main() { string filePath = "your_text_file.txt"; using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { // Match all non-whitespace characters before a colon MatchCollection matches = Regex.Matches(line, @"(\S+):"); foreach (Match match in matches) { Console.WriteLine(match.Groups[1].Value); } } } } }
The regex (\S+): targets any sequence of non-whitespace characters right before a colon, which directly gives you the names you need.
内容的提问来源于stack exchange,提问作者Jeroen Velde

