【问题标题】:How to get the char count between two indexes in a string?如何获取字符串中两个索引之间的字符数?
【发布时间】:2011-01-23 16:32:46
【问题描述】:
private IEnumerable<Player> GetGamePlayers(string content, string map)
{
    List<Player> Players = new List<Player>();

    var positions = new List<int>();

    for (int i = 0; i < 5; i++)
    {
        positions.Add(content.IndexOf(String.Format("[{0}] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)", i)));
    }

    for (int i = 0; i < 5; i++)
    {
        positions.Add(content.IndexOf(String.Format("[{0}] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)", i), positions[4] + 500));
    }

    foreach (var position in positions)
    {
        //NEED HELP HERE!
        var section = content.Substring(position, )
        Players.Add(ParsePlayer(section));
    }

    return Players;
}

位置变量保存我需要的部分的开始索引。

所以基本上,我需要一个从 position[0] 到 position[1] - 1 的子字符串。

有什么建议吗?

【问题讨论】:

  • 从您的代码中不清楚您要做什么,但您可以减去索引以获得它们之间的字符数!
  • 哦,你能做到吗?所以:var count = position[1] - position[0];?
  • 根据您对“介于”的定义,您可能需要加或减 1。当然,这取决于您如何定义字符。由于在 UTF-16 中,一个代码点并不总是对应于 System.Char。并且 unicode-codepoint 并不总是对应于单个渲染符号。

标签: c# string indexing


【解决方案1】:

既然需要索引,为什么不使用常规的 for 循环:

for (int i = 0; i < positions.Count-1; i++)
{
        string section = content.Substring(positions[i], 
                                           positions[i+1]-positions[i]);
        Players.Add(ParsePlayer(section));
}

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2012-12-28
    • 1970-01-01
    相关资源
    最近更新 更多