Home > Net >  How can I get the index of second comma?
How can I get the index of second comma?

Time:10-30

        //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));
        string blockLetter = csvString.Substring(firstComma   1, secondComma);
        Boolean lit = Boolean.Parse(csvString.Substring(secondComma   1));

        //print
        Console.WriteLine("Pyramid Slot Number: "   slotNumber);
        Console.WriteLine("Block Letter: "   blockLetter);
        Console.WriteLine("Lit: "   lit);

I tried to input like "5,M,true". However output for Block Letter is "M,t". If I try to input 15 instead of 5, then it gives "M,tr". In the end, I want to get only one letter. I'll use char after I figure this problem out.

Edit: char blockLetter = char.Parse(csvString.Substring(firstComma 1, 1)); I used this thank you!

CodePudding user response:

As I understand, based on code provided, you want the values delimited by commas. If I guessed correctly, then better use String.Split method.

CodePudding user response:

If your CSV file contains the data you anyway read, you could just split the string on comma and then extract individual fields by indices. Here is an example:

var csvEntry = "5,M,true";
var entryData = csvEntry.Split(',');

var slotNumber = int.Parse(entryData[0]);
var blockLetter = entryData[1];
var lit = bool.Parse(entryData[2]);

Console.WriteLine($"Pyramid Slot Number: {slotNumber}");
Console.WriteLine($"Block Letter: {blockLetter}");
Console.WriteLine($"Lit: {lit}");

CodePudding user response:

The first parameter of String.Substring is the start index, the second parameter is not the end index but the length. So you need to calculate it:

int startIndex = firstComma   1;
int length = secondComma - startIndex;
string blockLetter = csvString.Substring(startIndex, length);

An easier way is to use String.Split to get a string[] with all tokens delimited by comma:

string[] allSlots = csvString.Split(',');
// first token is in allSlots[0] and second in allSlots[1]
  • Related