2

我需要从字符串末尾获取单词。例如:

string1 = "Hello : World";
string2 = "Hello : dear";
string3 = "We will meet : Animesh";

我想要输出

string1 = "World"
string2 = "dear"
string3 = "Animesh"

我想要后面的词:

4

4 回答 4

11

各种方式:

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

Clicky clicky - 现场示例

编辑:

回应您的评论。索引 1 不适用于不包含冒号字符的字符串。您必须先检查:

var str = "Hello World";
var parts = str.Split(':');
var result = "";
if (parts.Length > 1)
    result = parts[1];
else
    result = parts[0];

Clicky clicky - 另一个现场样本

于 2013-10-28T03:27:36.113 回答
7

您可以使用Split

string s = "We will meet : Animesh";
string[] x = s.Split(':');
string out = x[x.Length-1];
System.Console.Write(out);

更新以响应 OP 的评论。

if (s.Contains(":"))
{
  string[] x = s.Split(':');
  string out = x[x.Length-1];
  System.Console.Write(out);
}
else
  System.Console.Write(": not found"); 
于 2013-10-28T03:30:03.077 回答
2

尝试这个

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();
于 2013-10-28T04:08:48.647 回答
1

正则表达式是解析任何文本并提取所需内容的好方法:

Console.WriteLine (
   Regex.Match("Hello : World", @"[^\s]+", RegexOptions.RightToLeft).Groups[0].Value);

与其他响应不同,此方法将起作用,即使没有:.

于 2013-10-28T03:58:01.500 回答