简体   繁体   English

在逗号和 x 个字符后拆分字符串

[英]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.我试图在最后一个逗号之后获取字符串中的前 6 个字符。 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.我很好地拆分了字符串,并添加了 6 个字符,但我的结果现在包括 6 个字符和逗号。

I have input similar to this: "VILLEDA URIBE,PAUL,BU2960"我有类似这样的输入:“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.我会得到一个 BU2960 的 output,这很好。

My problem is sometimes my input is like this: "BENTANCOURT,MARIA,BU2960_1_1"我的问题是有时我的输入是这样的:“BENTANCOURT,MARIA,BU2960_1_1”

I only want the 6 characters after the last comma.我只想要最后一个逗号后的 6 个字符。 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所以我的 output 是这个,BU2690

Not sure exactly how to make this work where I get the 6 characters after the comma as my output.不确定如何在逗号后的 6 个字符作为我的 output 的情况下进行这项工作。

I resolved this almost immediately after posting the question.我在发布问题后几乎立即解决了这个问题。 I needed to swap the ",6" after the "+ 1" so the code is:我需要在“+ 1”之后交换“,6”,所以代码是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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