使用 C# 查找字符串中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10709821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:56:04  来源:igfitidea点击:

Find text in string with C#

c#stringfind

提问by Wilson

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:

如何在字符串中找到给定的文本?在那之后,我想在它和其他东西之间创建一个新的字符串。例如,如果字符串是:

This is an example string and my data is here

And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.

我想用“我的”和“是”之间的任何内容创建一个字符串,我该怎么做?这是相当伪的,但希望它是有道理的。

采纳答案by Oscar Jara

Use this method:

使用这个方法:

public static string getBetween(string strSource, string strStart, string strEnd)
{
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        int Start, End;
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }

    return "";
}

How to use it:

如何使用它:

string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");

回答by Kevin DiTraglia

 string string1 = "This is an example string and my data is here";
 string toFind1 = "my";
 string toFind2 = "is";
 int start = string1.IndexOf(toFind1) + toFind1.Length;
 int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
 string string2 = string1.Substring(start, end - start);

回答by Lori Lalonde - MSFT

If you know that you always want the string between "my" and "is", then you can always perform the following:

如果你知道你总是想要“my”和“is”之间的字符串,那么你总是可以执行以下操作:

string message = "This is an example string and my data is here";

//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;

//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);

//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();

回答by MichelZ

You could use Regex:

您可以使用正则表达式:

var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
    var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
    Console.WriteLine("This is my captured text: {0}", myCapturedText);
}

回答by Kemal Duran

This is the simplest way:

这是最简单的方法:

if(str.Contains("hello"))

回答by RAMESH

static void Main(string[] args)
    {

        int f = 0;
        Console.WriteLine("enter the string");
        string s = Console.ReadLine();
        Console.WriteLine("enter the word to be searched");
        string a = Console.ReadLine();
        int l = s.Length;
        int c = a.Length;

        for (int i = 0; i < l; i++)
        {
            if (s[i] == a[0])
            {
                for (int K = i + 1, j = 1; j < c; j++, K++)
                {
                    if (s[K] == a[j])
                    {
                        f++;
                    }
                }
            }
        }
        if (f == c - 1)
        {
            Console.WriteLine("matching");
        }
        else
        {
            Console.WriteLine("not found");
        }
        Console.ReadLine();
    }

回答by Prashant

You can do it compactly like this:

你可以像这样紧凑地做到这一点:

string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);

回答by Fandango68

Except for @Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".

除@Prashant 的回答外,以上回答均已答错。答案的“替换”功能在哪里?OP 问道:“在那之后,我想在它和其他东西之间创建一个新的字符串”。

Based on @Oscar's excellent response, I have expanded his function to be a "Search And Replace"function in one.

基于@Oscar 的出色回应,我将他的功能扩展为"Search And Replace"功能合二为一。

I think @Prashant's answer should have been the accepted answer by the OP, as it does a replace.

我认为@Prashant 的答案应该是 OP 接受的答案,因为它确实替代了。

Anyway, I've called my variant - ReplaceBetween().

无论如何,我已经将我的变体称为 - ReplaceBetween()

public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        string strToReplace = strSource.Substring(Start, End - Start);
        string newString = strSource.Concat(Start,strReplace,End - Start);
        return newString;
    }
    else
    {
        return string.Empty;
    }
}

回答by Reza Taibur

  string WordInBetween(string sentence, string wordOne, string wordTwo)
        {

            int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;

            int end = sentence.IndexOf(wordTwo) - start - 1;

            return sentence.Substring(start, end);


        }

回答by Johnny Cee

Here's my function using Oscar Jara's function as a model.

这是我使用 Oscar Jara 的函数作为模型的函数。

public static string getBetween(string strSource, string strStart, string strEnd) {
   const int kNotFound = -1;

   var startIdx = strSource.IndexOf(strStart);
   if (startIdx != kNotFound) {
      startIdx += strStart.Length;
      var endIdx = strSource.IndexOf(strEnd, startIdx);
      if (endIdx > startIdx) {
         return strSource.Substring(startIdx, endIdx - startIdx);
      }
   }
   return String.Empty;
}

This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.

此版本最多对文本进行两次搜索。它避免了 Oscar 版本在搜索仅出现在开始字符串之前的结束字符串时抛出的异常,即getBetween(text, "my", "and");

Usage is the same:

用法是一样的:

string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");