Search code examples
vb.netstring-parsing

Parse stringto get final end result


I'm trying to parse this string 'Smith, Joe M_16282' to get everything before the comma, combined with everything after the underscore.

The resulting string would be: Smith16282


Solution

  • string longName = "Smith, Joe M_16282";
    
    string shortName = longName.Substring(0, longName.IndexOf(",")) + longName.Substring(longName.LastIndexOf("_") + 1);
    

    Notes:

    • The second "substring" doesn't need a length parameter, because we want everything after the underscore
    • The LastIndexOf is used instead of IndexOf in case there are other underscores appearing in the name such as "Smith_Jones, Joe M_16282"
    • This code assumes that there is at least one comma and at least one underscore in the string "longName." If not, the code fails. I will leave that checking to you if you need it.