Reputation: 341
I need to get the words from the end of a string. For example:
string1 = "Hello : World";
string2 = "Hello : dear";
string3 = "We will meet : Animesh";
I want output for
string1 = "World"
string2 = "dear"
string3 = "Animesh"
I want the word after the :
.
Upvotes: 2
Views: 3848
Reputation: 31596
Regular Expressions is a good way to parse any texts and extract out what is needed:
Console.WriteLine (
Regex.Match("Hello : World", @"[^\s]+", RegexOptions.RightToLeft).Groups[0].Value);
This method will work, unlike the other responses, even when there is no :
.
Upvotes: 1
Reputation: 3752
You can use Split
string s = "We will meet : Animesh";
string[] x = s.Split(':');
string out = x[x.Length-1];
System.Console.Write(out);
Update in response to OPs' comment.
if (s.Contains(":"))
{
string[] x = s.Split(':');
string out = x[x.Length-1];
System.Console.Write(out);
}
else
System.Console.Write(": not found");
Upvotes: 7
Reputation: 65059
Various ways:
var str = "Hello : World";
var result = str.Split(':')[1];
var result2 = str.Substring(str.IndexOf(":") + 1);
EDIT:
In response to your comment. Index 1 won't be available for a string that does not contain a colon character. You'll have to check first:
var str = "Hello World";
var parts = str.Split(':');
var result = "";
if (parts.Length > 1)
result = parts[1];
else
result = parts[0];
Clicky clicky - Another live sample
Upvotes: 11
Reputation: 1439
Try this
string string1 = "Hello : World";
string string2 = "Hello : dear";
string string3 = "We will meet : Animesh";
string1 = string1.Substring(string1.LastIndexOf(":") + 1).Trim();
string2 = string2.Substring(string2.LastIndexOf(":") + 1).Trim();
string3 = string3.Substring(string3.LastIndexOf(":") + 1).Trim();
Upvotes: 2