【问题标题】:"Index and length must refer to a location within the string" when I'm trying to create a substring当我尝试创建子字符串时,“索引和长度必须引用字符串中的位置”
【发布时间】:2014-02-16 23:03:39
【问题描述】:

我收到此错误,但我似乎无法理解原因。

    private void MessageReceived(String message)
    {
        int beginIndex = message.IndexOf(":");
        String index = message.Substring(1, beginIndex - 1);
        if (index == "SHOW_TIME")
        {
            String time = message.Substring(11, message.Length -1);
            if (alarm == time)
            {
                MessageBox.Show("ALARM ALARM ALARM ALARM");
            }
        }
    }

程序到达String时间线时弹出错误。

【问题讨论】:

  • 假设你的字符串(消息)不包含:或者它的长度小于11
  • 消息字符串包含:#SHOW_TIME:xxxx%

标签: c# string indexing substring


【解决方案1】:

您从索引 11 开始,但尝试一直到 message.Length - 1。这会将您置于导致错误的数组末尾之外。你需要一直到message.Length - 12

String time = message.Substring(11, message.Length - 12);

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多