C# 字符串函数

C# 字符串函数,c#,string,C#,String,我想在另一个字符串中搜索给定的字符串(例如,查找“类似于此的东西”中是否存在“某物”)。如何执行以下操作: 知道“某物”所在的位置(例如,这是=0) 从左边或右边提取所有内容,直到char.found(见1) 从查找到的字符串所在的位置提取一个子字符串,一直到X个字符(在Visual Basic 6/VBA中,我将使用Mid函数) 您看过String.SubString()方法了吗?您可以先使用IndexOf()方法查看子字符串是否存在。看看成员函数,特别是方法 一, 二, 三, 使用。我会这样

我想在另一个字符串中搜索给定的字符串(例如,查找“类似于此的东西”中是否存在“某物”)。如何执行以下操作:

  • 知道“某物”所在的位置(例如,这是=0)
  • 从左边或右边提取所有内容,直到char.found(见1)
  • 从查找到的字符串所在的位置提取一个子字符串,一直到X个字符(在Visual Basic 6/VBA中,我将使用Mid函数)

  • 您看过String.SubString()方法了吗?您可以先使用IndexOf()方法查看子字符串是否存在。

    看看成员函数,特别是方法

    一,

    二,

    三,


    使用。

    我会这样做:

    string s = "I have something like this";
    
    //question No. 1
    int pos = s.IndexOf("something");  
    
    //quiestion No. 2
    string[] separator = {"something"};
    string[] leftAndRightEntries = s.Split(separator, StringSplitOptions.None);  
    
    //question No. 3
    
    int x = pos + 10;
    string substring = s.Substring(pos, x);
    

    我会避免使用Split,因为它的设计是为了给你多个结果

    string start = searched.Substring(0, pos);
    string endstring;
    
    if(pos < searched.Length - 1)
    endstring = searched.Substring(pos + "something".Length);
    else
    endstring = string.Empty
    
    string start=searched.Substring(0,pos);
    字符串结束字符串;
    如果(位置<搜索长度-1)
    endstring=searched.Substring(pos+“something.Length”);
    其他的
    endstring=string.Empty
    

    关键的区别在于要查找的字符串的长度(因此是看起来很奇怪的“something”。length,因为本例旨在让您能够在自己的变量中使用plop)。

    @bdukes:感谢您的编辑,我仍然缺少“something”周围的引号之后。由于没有考虑“某物”的长度,所以数字2不起作用。使用拆分方法更容易。@Igor:取决于您对#2的解释。“直到char.found(见1)。”对我来说,这意味着IndexOf返回的内容。对于您的解释,您的方法是有效的。效果很好。我如何将其编码到一个类中,该类对任何Visual Studio项目都是公开的?是的,这也很有效,但OP正在寻找提取子字符串的方法。Contains()只会告诉他是否能找到。在这种情况下,IndexOf会更有用
    string start = searched.Substring(0, pos);
    string endstring = searched.Substring(pos);
    
    string mid = searched.Substring(pos, x);
    
    string s = "I have something like this";
    
    //question No. 1
    int pos = s.IndexOf("something");  
    
    //quiestion No. 2
    string[] separator = {"something"};
    string[] leftAndRightEntries = s.Split(separator, StringSplitOptions.None);  
    
    //question No. 3
    
    int x = pos + 10;
    string substring = s.Substring(pos, x);
    
    string start = searched.Substring(0, pos);
    string endstring;
    
    if(pos < searched.Length - 1)
    endstring = searched.Substring(pos + "something".Length);
    else
    endstring = string.Empty