Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string value in C#

Tags:

c#

.net

split

I have a string value which I need to get the middle bit out of, e.g. "Cancel Payer" / "New Paperless".

These are examples of the string format:

"REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf"
"REF_SPHCPHJ0000056_New Paperless_20100105174151.pdf"

like image 269
MartGriff Avatar asked Jan 08 '10 13:01

MartGriff


People also ask

How do you split a string into values?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

What is string split () and give its syntax?

public String[] split(String regex)This variant of the split method takes a regular expression as a parameter and breaks the given string around matches of this regular expression regex. Here, by default limit is 0. Returns: An array of strings is computed by splitting the given string.

What does strtok () do in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.

What is split () method?

Definition and Usage. The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

Use:

string s = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middleBit = s.Split('_')[2];
Console.WriteLine(middleBit);

The output is

Cancel Payer
like image 55
jason Avatar answered Sep 23 '22 02:09

jason


This is a place for regular expressions:

Regex re = new Regex(@".*_(?<middle>\w+ \w+)_.*?");
string name = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middle = re.Match(name).Groups["middle"].Value;
like image 41
Rubens Farias Avatar answered Sep 20 '22 02:09

Rubens Farias