John Parham
John Parham

Reputation: 21

Split string after comma and x number of characters

I am trying to get the first 6 characters in a string after the last comma. I'm splitting the string just fine, and I added for 6 characters, but my results are now including the 6 characters and the comma.

I have input similar to this: "VILLEDA URIBE,PAUL,BU2960"

I basically use this, and it works fine:

string last = str.Substring(str.LastIndexOf(',') + 1);

I'll get an output of BU2960, which is fine.

My problem is sometimes my input is like this: "BENTANCOURT,MARIA,BU2960_1_1"

I only want the 6 characters after the last comma. I've tried this:

string last = str.Substring(str.LastIndexOf(','), 6 + 1);

But now my results include the comma. So my output is this ,BU2690

Not sure exactly how to make this work where I get the 6 characters after the comma as my output.

Upvotes: 0

Views: 834

Answers (1)

John Parham
John Parham

Reputation: 21

I resolved this almost immediately after posting the question. I needed to swap the ",6" after the "+ 1" so the code is:

string last = str.Substring(str.LastIndexOf(',') + 1, 6);

Upvotes: 2

Related Questions