【问题标题】:How can I get the index of second comma?如何获取第二个逗号的索引?
【发布时间】:2021-12-15 02:24:44
【问题描述】:
        //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);

我尝试输入“5,M,true”。然而,Block Letter 的输出是“M,t”。如果我尝试输入 15 而不是 5,那么它会给出“M,tr”。最后,我只想收到一封信。解决这个问题后我会使用char。

编辑: char blockLetter = char.Parse(csvString.Substring(firstComma + 1, 1)); 我用这个谢谢!

【问题讨论】:

  • 我认为你的代码中的错误是使用了 Substring 方法,应该传递 (index, length),而你传递 (index, other_index)。您需要通过 (index, other_index - index) 代替。见docs.microsoft.com/pl-pl/dotnet/api/…

标签: c# .net string indexof


【解决方案1】:

String.Substring的第一个参数是开始索引,第二个参数不是结束索引而是长度。所以你需要计算一下:

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

一种更简单的方法是使用String.Split 来获得一个string[],其中所有标记都用逗号分隔:

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

【讨论】:

    【解决方案2】:

    据我了解,根据提供的代码,您需要用逗号分隔的值。如果我猜对了,那么最好使用String.Split 方法。

    【讨论】:

      【解决方案3】:

      如果您的 CSV 文件包含您无论如何读取的数据,您可以用逗号分割字符串,然后按索引提取各个字段。这是一个例子:

      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}");
      

      【讨论】:

        猜你喜欢
        • 2014-05-05
        • 2021-12-17
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多