nemo_87
nemo_87

Reputation: 4791

Substring from character to character in C#

How can I get sub-string from one specific character to another one?

For example if I have this format:

string someString = "1.7,2015-05-21T09:18:58;";

And I only want to get this part: 2015-05-21T09:18:58

How can I use Substring from , character to ; character?

Upvotes: 1

Views: 6956

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

Use regex,

@"(?<=,).*?(?=;)"

This would extract all the chars next to , symbol upto the first semicolon.

Upvotes: 1

Vishal Suthar
Vishal Suthar

Reputation: 17194

This would be better:

string input = "1.7,2015-05-21T09:18:58;";
string output = input.Split(',', ';')[1];

Using SubString:

public string FindStringInBetween(string Text, string FirstString, string LastString)
{
    string STR = Text;
    string STRFirst = FirstString;
    string STRLast = LastString;
    string FinalString;

    int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
    int Pos2 = STR.IndexOf(LastString);

    FinalString = STR.Substring(Pos1, Pos2 - Pos1);
    return FinalString;
} 

Try:

string input = "1.7,2015-05-21T09:18:58;";
string output = FindStringInBetween(input, ",", ";");

Demo: DotNet Fiddle Demo

Upvotes: 2

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98868

If you string has always one , and one ; (and ; after your ,), you can use combination of IndexOf and Substring like;

string someString = "1.7,2015-05-21T09:18:58;";
int index1 = someString.IndexOf(',');
int index2 = someString.IndexOf(';');

someString = someString.Substring(index1 + 1, index2 - index1 - 1);
Console.WriteLine(someString); // 2015-05-21T09:18:58

Here a demonstration.

Upvotes: 3

Related Questions