2

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 :.

1
  • 1
    Did you check string.Split ? Commented Oct 28, 2013 at 3:27

4 Answers 4

11

Various ways:

var str = "Hello : World";
var result = str.Split(':')[1];
var result2 = str.Substring(str.IndexOf(":") + 1);

Clicky clicky - Live sample

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

Sign up to request clarification or add additional context in comments.

2 Comments

:: When I use it normally it works fine. But when I use in datagridview it shows an error. "Index was outside the bounds of the array." on 2nd line
That is because the string you're passing to it doesn't contain a colon character. To fix that, you'll have to check the length.. I will update my answer.
7

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"); 

2 Comments

When I use it normally it works fine. But when I use in datagridview it shows an error. "DataGridViewComboBoxCell { ColumnIndex=0, RowIndex=0 }".
Does all your string have the colon (:) character? If the string does not have it, then there will be an error. Let me update the answer. Also what will happen if you do not have the : in your string?
2

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();

Comments

1

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 :.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.