简体   繁体   中英

String.Substring Method (Int32, Int32) throws ArgumentOutOfRangeException

I have a string where the first 5 characters are never empty and from char 6 to the end data is variable leght. Something like this:

string inData = comPort1.ReadExisting();
//Console.WriteLine("inData: " + inData);
string origMsg = inData.Substring(4, 1);
//Console.WriteLine("origMsg: " + origMsg);
string seAnex = inData.Substring(5, 15);           // ArgumentOutOfRangeException
inData = inData.Substring(5, inData.Length - 8);
//Console.WriteLine("new inData: " + inData);

if (seAnex == "some_text_15_ch")
{
    //...
}
else
{
    //...
}

Output:

inData: {1112Test}
origMsg: 2
new inData: Test

This code throws a ArgumentOutOfRangeException: Index and length must refer to a location within the string . How can I solve this?

string origMsg = inData.Substring(4, 1);

"startIndex cannot be larger than length of string"

in other words,

4 cannot be larger than length of inData

4 is larger than length of inData

inData.Length is less than 4

I'm not sure what do you want to do with your code. But, if just to resolve the exception. You can fix like this:

        string inData = comPort1.ReadExisting();
        //Console.WriteLine("inData: " + inData);
        if (inData.Length >= 5)
        {
            string origMsg = inData.Substring(4, 1);
            //Console.WriteLine("origMsg: " + origMsg);
            //string seAnex = inData.Substring(5, 15);           // ArgumentOutOfRangeException
            string seAnex = inData.Substring(5, inData.Length - 5);
            //inData = inData.Substring(5, inData.Length - 8);
            //Console.WriteLine("new inData: " + inData);

            if (seAnex == "some_text_15_ch")
            {
                //...
            }
            else
            {
                //...
            }
        }

I guess your purpose can be get data information from a message have format like "{111abcxzy}" in a long data string "{111abcxzy}{111abcxzy}{..." that received from COM communication ?

I would bet that you do not have the string value you say that you do. If it were in fact 5+ characters long, you would not have and ArgumentOutOfRange exception when you call SubString(4,1) on it. Print out the value or inspect it in the debugger to confirm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM