简体   繁体   中英

Mid$ function translate from VB6 to C#

I am not a VB6-ish person. I just need to translate some codes from VB6 to C# for our project. I have this code on VB6

Comm_ReceiveData = Mid$(Comm_ReceiveData, 2, Len(Comm_ReceiveData))

This code is found inside Timer1_Timer() subfunction.

I converted this line to C#

Comm_ReceiveData = Comm_ReceiveData.Substring(1, Comm_ReceiveData.Length);

So in C#, I received this error.

Index and length must refer to a location within the string.

The string Comm_ReceiveData is "01BP215009010137\\r". Length, I believe, is 17

Yes, I know I will get this kind of error in C#. I wonder why I do not get error on VB6. Is there another way to translate that VB6 code to C#? Is that VB6 Code not sensitive to "out-of-bounds" kind of error?

BTW, I'm using that code for serial communication. I'm getting a string from my arduino going to C#/VB6 and I need to decode it. Thank you very much!

Comm_ReceiveData = Comm_ReceiveData.Substring(1);

should do the trick. Substring has a one-argument version that just needs the start position of the substring.

The Mid$ function returns up to the specified length. If there are fewer characters than the length then it returns (without error) what characters there are from the start position to the end of the string. The VB6 code you show rather sloppily counts on that specific behavior of Mid$, and is unnecessary besides since Mid$ would behave the same if they had just omitted the length parameter entirely. This page explains: http://www.thevbprogrammer.com/Ch04/04-08-StringFunctions.htm

So the literal equivalent in C# would be

Comm_ReceiveData = Comm_ReceiveData.Substring(1, Comm_ReceiveData.Length-1);

But FrankPl's answer has the variant of Substring that makes more sense to use.

The Mid$ graciously handles out of bounds errors by either returning as best a substring as it can, or by returning the source string.

This method reproduces the behavior of the Mid$ function from VB6 for C#.

/// <summary>
/// Function that allows for substring regardless of length of source string (behaves like VB6 Mid$ function)
/// </summary>
/// <param name="s">String that will be substringed</param>
/// <param name="start">start index (0 based)</param>
/// <param name="length">length of desired substring</param>
/// <returns>Substring if valid, otherwise returns original string</returns>
public static string Mid(string s, int start, int length)
{
    if (start > s.Length || start < 0)
    {
        return s;
    }

    if (start + length > s.Length)
    {
        length = s.Length - start;
    }

    string ret = s.Substring(start, length);
    return ret;
}

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