C# 使用子字符串获取字符串前的数字

C# 使用子字符串获取字符串前的数字,c#,C#,我正在读一个C语言的文件。我想检查字符串中的值。该行包括以下内容: 15 EMP_L_NAME HAPPENS 5 TIMES. 40 SUP HAPPENS 12 TIMES. 我想在字符串“times”之前找到字符串中的次数。我编写了以下代码: int arrayLength = 0; int timesindex = line.IndexOf("TIMES"); if (timesindex > 0) {

我正在读一个C语言的文件。我想检查字符串中的值。该行包括以下内容:

   15  EMP_L_NAME HAPPENS 5 TIMES.   
   40  SUP HAPPENS 12 TIMES. 
我想在字符串“times”之前找到字符串中的次数。我编写了以下代码:

     int arrayLength = 0;
     int timesindex = line.IndexOf("TIMES"); 
     if (timesindex > 0)
     {
          //Positon of the digit "5" in the first line
          int indexCount = timesindex - 2;
          if (int.TryParse(line.Substring(indexCount, 1), out occursCount)) 
          {
                  arrayLength = occursCount;
           }
      }

使用上面的代码,我可以找到单个数字的“次数”。但如果是两位数,则不起作用(例如第二行)。我必须发展一种逻辑来找到由一个带有“TIMES”的空格分隔的数字。我该怎么做?

如果输入可靠,您可以使用
String.Split()

int arrayLength = 0;
int timesindex = line.IndexOf("TIMES"); 
if (timesindex > 0)
{
    string[] items = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
    if (int.TryParse(items[items.Length - 2], out occursCount)) 
    {
        arrayLength = occursCount;
    }
}

此方法依赖于所需的数字是每行最后一个“单词”的倒数第二个

如果字符串的格式始终相同,只有五个单词或“部分”或任何您想调用的内容,则可以使用:

int times = 0;
Int32.TryParse(line.Split(' ')[3], out times);
这必须更加可靠,因为数字可能不存在于字符串中,或者字符串的格式完全不同。

您可以执行以下操作:

  • 在空格上拆分字符串并删除空的条目
  • 查找“时间”索引
  • 访问元素索引-1
比如:

结合您的
时间索引查看。您可以在空格之前查找空格(
timeindex
-1),然后在数字周围找到两个位置

int timesindex = line.IndexOf("TIMES");
int firstSpace = line.LastIndexOf(" ", timesindex-1);
string number = line.Substring(firstSpace, timesindex-firstSpace);
虽然这可能需要对索引进行一些调整,但无论如何,这就是想法

int timesindex = line.IndexOf("TIMES");
int happensindex = line.IndexOf("HAPPENS") + 7; //Add 7 cause HAPPEND is 7 chars long
if (timesindex > 0)
{
    //Positon of the digit "5" in the first line
    if (int.TryParse(line.Substring(happensindex, timesindex).trim(), out occursCount)) 
    {
        arrayLength = occursCount;
    }
}

您可以使用
System.Text.RegularExpressions.Regex
,即正则表达式,以便在字符串中查找模式:

string input = "40  SUP HAPPENS 12 TIMES.";
Match match = Regex.Match(input, @"(?<=HAPPENS\s)\d+(?=\sTIMES)");
if (match.Success) {
    Console.WriteLine(match.Value); '==> "12"
}

由于您多次使用相同的搜索模式,建议创建一次
Regex
,而不是调用静态方法:

Regex regex = new Regex(@"\d+(?=\sTIMES)");

// Use many times with different inputs
Match match = regex.Match(input);

正则表达式会更干净:

var regex = new Regex(@"(\d+)\sTIMES");  // match a number followed by whitespace then "TIMES"
string num = regex.Match(" 15  EMP_L_NAME HAPPENS 5 TIMES").Groups[1].ToString();
int val = int.Parse(num);
使用LINQ:

string[] lines = {"15  EMP_L_NAME HAPPENS 5,1 TIMES.", "40  SUP HAPPENS 12 TIMES. "};

var allValues = lines.Select(line =>
            {
                double temp;
                var words = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                var value = words[Array.IndexOf(words,"TIMES.") - 1];
                if (double.TryParse(value, out temp)) return temp;
                else return 0;
            }).ToList();

            foreach (var value in allValues)
            {
                Console.WriteLine(value);
            }  

// Output:
//   5,1
//   12

您必须找到
发生的结束时间
时间的开始时间
。获取介于两者之间的值,并使用
trim()
清除空格。好了
Regex regex = new Regex(@"\d+(?=\sTIMES)");

// Use many times with different inputs
Match match = regex.Match(input);
var regex = new Regex(@"(\d+)\sTIMES");  // match a number followed by whitespace then "TIMES"
string num = regex.Match(" 15  EMP_L_NAME HAPPENS 5 TIMES").Groups[1].ToString();
int val = int.Parse(num);
string[] lines = {"15  EMP_L_NAME HAPPENS 5,1 TIMES.", "40  SUP HAPPENS 12 TIMES. "};

var allValues = lines.Select(line =>
            {
                double temp;
                var words = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                var value = words[Array.IndexOf(words,"TIMES.") - 1];
                if (double.TryParse(value, out temp)) return temp;
                else return 0;
            }).ToList();

            foreach (var value in allValues)
            {
                Console.WriteLine(value);
            }  

// Output:
//   5,1
//   12