【问题标题】:Getting a Text between two texts [duplicate]在两个文本之间获取文本[重复]
【发布时间】:2014-07-22 08:39:52
【问题描述】:

我正在尝试获取位于两个单词之间的文本。

项目名称 - 这是我要获取的文本,联系人姓名 -

如何在没有第一个文本和最后一个文本的情况下准确获得项目名称?

我试过这段代码,但它也需要联系人姓名内容:

int Place1 = SecondText.IndexOf("Project Name");
int Place2 = SecondText.IndexOf("Contact Name");
Name = SecondText.Substring(Place1, Place2);
NameTB.Text = Name;

我创建了一个 Cleaner 函数,它删除了项目名称和联系人姓名这两个词 但联系人姓名保留在我的字符串中。

感谢您的帮助。

【问题讨论】:

  • 您最好使用正则表达式。正则表达式专为模式匹配而设计。

标签: c# string


【解决方案1】:

这样说:

  String SecondText = "Project Name - this is the text I want to get, Contact Name -";

  // Pay attention to + + "Project Name".Length; and - Place1
  int Place1 = SecondText.IndexOf("Project Name") + "Project Name".Length;
  int Place2 = SecondText.IndexOf("Contact Name") - Place1;
  Name = SecondText.Substring(Place1, Place2);

【讨论】:

  • 感谢 Dimitry,效果很好。即使这个也有效:Name = SecondText.Substring(Place1, Place2 - Place1);
【解决方案2】:

试试这个代码

string SecondText = "Project Name - this is the text I want to get, Contact Name";
string result = SecondText.Replace("Project Name - ","");
int Place2 = result.IndexOf(", Contact Name");
string Name = result.Substring(0, Place2);

我希望这对你有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 2021-02-07
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2023-02-13
    相关资源
    最近更新 更多