如何获取字符串中第二个逗号的索引?C#字符串截取异常问题解决
Hey there! Let's break down your two questions and fix that CSV parsing issue:
1. How to get the index of the second comma in a string?
To find the second comma, use the overloaded version of IndexOf that lets you specify a starting position for the search. Here's the straightforward approach:
- First, grab the index of the first comma with
string.IndexOf(',') - Then, start searching from the position right after the first comma (
firstComma + 1) to locate the second comma:int firstComma = csvString.IndexOf(','); int secondComma = csvString.IndexOf(',', firstComma + 1);
For example, in the string "5,M,true", the first comma sits at index 1. Starting the search at index 2 finds the second comma at index 3.
2. Fixing the Block Letter extraction issue
The problem in your original code stems from a common misunderstanding of C#'s Substring method: the second parameter is the length of the substring to take, not the ending index.
Your original line:
string blockLetter = csvString.Substring(firstComma + 1, secondComma);
In the input "5,M,true", firstComma + 1 equals 2, and secondComma equals 3. This tells Substring to take 3 characters starting at index 2, which gives you "M,t" instead of just "M".
Your corrected solution is spot-on!
You already fixed this by explicitly taking 1 character after the first comma—perfect for your use case since you want a single char:
char blockLetter = char.Parse(csvString.Substring(firstComma + 1, 1));
If you ever need to handle longer values between commas (though you noted you want a char), you could calculate the exact length between the two commas like this:
string blockLetter = csvString.Substring(firstComma + 1, secondComma - (firstComma + 1));
Here's your full corrected code:
//read Console.Write("Please enter (pyramid slot number,block letter,whether or not the block should be lit): "); string csvString = Console.ReadLine(); //location of comma int firstComma = csvString.IndexOf(','); int secondComma = csvString.IndexOf(',', firstComma + 1); //extract slot number of pyramid int slotNumber = int.Parse(csvString.Substring(0, firstComma)); // Corrected: directly parse the single character after first comma char blockLetter = char.Parse(csvString.Substring(firstComma + 1, 1)); bool lit = bool.Parse(csvString.Substring(secondComma + 1)); //print Console.WriteLine("Pyramid Slot Number: " + slotNumber); Console.WriteLine("Block Letter: " + blockLetter); Console.WriteLine("Lit: " + lit);
内容的提问来源于stack exchange,提问作者MetroRN

