从字符串中提取文本

时间:2014-04-04 06:39:58

标签: c#

我需要提取文本字符串的一部分(在这种情况下,所有内容都在“Data Source =”之后。

“数据来源= xxxxx”

在VBA中,有一个函数调用Mid()

strText = "Data Source=xxxxx"
var = Mid(strText, 12)

C#中有类似内容吗?

3 个答案:

答案 0 :(得分:2)

您可以使用String.Substring(Int32) overload;

  

从此实例中检索子字符串。 子字符串从a开始   指定的字符位置并继续到字符串的末尾。

string strText = "Data Source=xxxxx";
string s = strText.Substring(12);

s将为xxxxx

这里有 demonstration

使用IndexOf方法或Split方法处理您的情况会更好IMO ..

string s = strText.Substring(strText.IndexOf('=') + 1);

string s = strText.Split(new []{'='}, StringSplitOptions.RemoveEmptyEntries)[1];

答案 1 :(得分:2)

你想要一个从12开始向外的子串:

var source = strText.Substring(12);

或者,您可以在=之后从索引开始(如果您想要其他设置中的类似内容):

var foundValue = strText.Substring(strText.IndexOf("=") + 1);

答案 2 :(得分:1)

试试这个

string originalText = "Data Source = whatever is your text here";
string consText = "Data Source =";

string result = originalText.Substring(originalText.IndexOf(consText) + consText.Length);

这将是实现您想要的最简单和最重要的方式,因为您只需要设置所需的constantText并在此文本之后获取所有内容。

相关问题