c# - 在字符串中的两个值之间查找单词

标签 c# .net string substring indexof

我有一个作为字符串的 txt 文件,我需要在两个字符和 Ltrim/Rtrim 之间找到单词。它可能必须是有条件的,因为这两个字符可能会根据字符串而改变。

示例:

car= (data between here I want) ;
car =  (data between here I want) </value>

代码:

int pos = st.LastIndexOf("car=", StringComparison.OrdinalIgnoreCase);

if (pos >= 0)
{
     server = st.Substring(0, pos);..............
}

最佳答案

这是我使用的一个简单的扩展方法:

public static string Between(this string src, string findfrom, string findto)
{
    int start = src.IndexOf(findfrom);
    int to = src.IndexOf(findto, start + findfrom.Length);
    if (start < 0 || to < 0) return "";
    string s = src.Substring(
                   start + findfrom.Length, 
                   to - start - findfrom.Length);
    return s;
}

有了这个你就可以使用

string valueToFind = sourceString.Between("car=", "</value>")

你也可以试试这个:

public static string Between(this string src, string findfrom, 
                             params string[] findto)
{
    int start = src.IndexOf(findfrom);
    if (start < 0) return "";
    foreach (string sto in findto)
    {
        int to = src.IndexOf(sto, start + findfrom.Length);
        if (to >= 0) return
            src.Substring(
                       start + findfrom.Length,
                       to - start - findfrom.Length);
    }
    return "";
}

有了这个你可以给出多个结束标记(它们的顺序很重要)

string valueToFind = sourceString.Between("car=", ";", "</value>")

关于c# - 在字符串中的两个值之间查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082103/

相关文章:

c# - DateTime 将 Linq 内部的计算添加到实体查询

c# - 更正 .NET 中 "mixed"类型的 XML 序列化和反序列化

.net - 是否可以以编程方式启动/停止 IIS 中的应用程序池或网站?

.NET:如何使用 Windows "Copy Files"对话框复制文件

java - 树形图条目转换为字符串类型失败

c# - 标记为只读的值类型字段的意外行为

c# - 如何在动态 Odata 对象上设置枚举值

c# - 在 asp.net mvc 的同一 View 中列出和创建

计算字符串或文件中的字符数

python - 将 float 转换为一定精度,然后复制为字符串