子字符串文本选择

时间:2013-12-10 22:21:54

标签: c# substring

我正在使用C#,并且具有以下字符串文本值:

get directions from Sydney to Melbourne

这是我目前尝试获取 From To

之间出现的文字的代码
String fromDestination = InputTextbox.Text;
if (fromDestination.Contains("from"))
{
   fromDestination = fromDestination.Substring(fromDestination.IndexOf("from") + 5, fromDestination.IndexOf("to") - 3);
}

该代码从返回的值中删除了“from”这个词,但我无法弄清楚如何获取“to”。目前的输出是: sydney to Melb

感谢您的帮助。

6 个答案:

答案 0 :(得分:1)

这是另一条可能的路线(lolpun)..

您可以通过“from”和“to”进行拆分。然后为您创建每个部分:

var str = "get directions from Sydney to Melbourne";

var parts = str.Split(new string[] { "from", "to" }, StringSplitOptions.None); // split it up
var from = parts[1]; // index 1 is from
var to = parts[2];   // index 2 is to

Console.WriteLine(from); // "Sydney"
Console.WriteLine(to);   // "Melbourne"

答案 1 :(得分:1)

传递给Substring方法的第二个参数是从实例字符串中提取的字符数,而不是另一个位置

String fromDestination = InputTextbox.Text;
int pos = fromDestination.IndexOf(" from ");
if(pos >= 0)
{
   int pos2 = fromDestination.IndexOf(" to ", pos);
   if(pos2 > -1)
   {
      int len = pos2 - (pos + 6);
      fromDestination = fromDestination.Substring(pos+6, len);

   }
}

请注意,我更改了在fromto之前和之后添加空格的搜索字符串。当城市名称包含“to”作为其名称的一部分或者在实际开始之前文本中嵌入了另一个from时,这是避免误报所需的预防措施from

答案 2 :(得分:0)

如果字符串始终相同,我建议使用简单的字符串拆分。

string fromDestination = InputTextbox.Text.Split(' ')[3];

答案 3 :(得分:0)

Substring(startIndex, length)

计算你应该尝试fromDestination.Length - fromDestination.IndexOf(" to ")

的长度
fromDestination.Substring(fromDestination.IndexOf(" from ") + 5, fromDestination.Length - fromDestination.IndexOf(" to "));

答案 4 :(得分:0)

您还可以使用正则表达式:

String fromDestination = "get directions from Sydney to Melbourne";
var match = Regex.Match(fromDestination, @"(?<=from\s).*(?=\sto)");
if (match.Groups.Count > 0)
    fromDestination = match.Groups[0].Value;

答案 5 :(得分:0)

这将为您提供字符串“悉尼墨尔本”:

string fromDestination = "get directions from Sydney to Melbourne";
string result = fromDestination.Substring(fromDestination.IndexOf("from") + 5).Replace("to", "");

从外观上看,您可能最好更换2个组合框的文本框,每个组合框的项目都由预定义的可用城市列表填充,因此用户无法输入任何拼写错误,例如您只需对组合框的selectedindex做出反应...

相关问题