C# 如何使用IndexOf获取字符串中的两个独立部分
我有一些接收结果(启动时间)的代码,并希望将这些结果粘贴到txt文件中 我试过使用下面的代码,但目前只得到了启动时间的索引和行的其余部分,但我似乎无法得到日期C# 如何使用IndexOf获取字符串中的两个独立部分,c#,indexing,C#,Indexing,我有一些接收结果(启动时间)的代码,并希望将这些结果粘贴到txt文件中 我试过使用下面的代码,但目前只得到了启动时间的索引和行的其余部分,但我似乎无法得到日期 using (var process = Process.Start(psi)) { results = process.StandardOutput.ReadToEnd(); } 您可以简单地使用正则表达式: string date = null, startup_time = null; var match = Regex.
using (var process = Process.Start(psi))
{
results = process.StandardOutput.ReadToEnd();
}
您可以简单地使用正则表达式:
string date = null, startup_time = null;
var match = Regex.Match(results, @"(\d{2}-\d{2}-\d{2} \d{2}:\d{2})");
if(match.Success)
{
date = match.Groups[1].Value;
}
match = Regex.Match(results, @"(scene startup time:\s*(\d+ms)");
if(match.Success)
{
startup_time = match.Groups[1].Value;
}
如果要使用IndexOf()
执行此操作:
首先,我将对
结果执行字符串分割,使用空格字符作为分隔符。这将为您提供一个包含结果中所有“单词”的数组。我建议使用正则表达式从整个字符串中提取时间戳。这将使它更容易,更不易碎。请看这篇文章和类似的例子:@blakeh这个问题发生了重大变化。已进行编辑以删除测试数据和预期数据。那是故意的吗?
string search = "Total scene startup time:";
int start = results.IndexOf(search) + search.Length;
string startup = results.Substring(start, results.IndexOf("ms", start + 1) + 2 - start).Trim();
Console.WriteLine(startup);