Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c# - First split then join a subset of a string

I have an input string as follows:

thumb_634735515600845357tchayat_november_200612.jpg

What I want to do is first split this string by _. And then take the resulting tokens at positions 1 to n and join them.

Specifically, with respect to my sample input, here is my desired output. As you can see, thumb_ has been removed from the front of the string:

634735515600845357tchayat_november_200612.jpg

I know how to do the split. But then how do I do the join step that follows? I do realize that I can use a for loop to do the join. But is there a better way? I can't use a sub-string approach to do the join step because I have data before thumb_.

Finally, note that the _ character that follows thumb is always the first instance of _.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since the _ after the thumb is always the first instance then Substring should be perfectly viable in conjunction with IndexOf.

string newString = myString.Substring(myString.IndexOf("_") + 1);

This should take the substring starting at the character immediately following the first instance of the _ character.

If you wish to get the second index of _, here's what I recommend:

int first = myString.IndexOf("_");
int second = mystring.Substring(first).IndexOf("_");

See this answer by Jon Skeet to the question "Index of the nth occurrence of a string?" for support for this approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...