【问题标题】:How to use IndexOf to get two separate parts in a string如何使用 IndexOf 获取字符串中的两个单独部分
【发布时间】:2021-07-22 08:05:49
【问题描述】:

我有一些代码用于接收结果(启动时间)并希望将这些结果与 txt 文件一起粘贴。

我尝试使用下面的代码,但目前只获取启动时间的索引和行的其余部分,但我似乎也无法获取日期。

using (var process = Process.Start(psi))
{
    results = process.StandardOutput.ReadToEnd();
}

【问题讨论】:

  • 我会首先在你的results 上做一个String.Split,使用空格字符作为分隔符。这将为您提供一个包含results 中所有“单词”的数组。
  • 我建议使用 RegEx 从整个字符串中提取时间戳。这将使它更容易和不那么脆弱。有关一些示例,请参阅此帖子和类似帖子:stackoverflow.com/questions/21723697/…
  • @blakeh 这个问题发生了很大变化。进行了编辑以删除测试和预期数据。是故意的吗?

标签: c# indexing


【解决方案1】:

您可以简单地使用正则表达式:

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()

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

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多