91

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

This is an example string and my data is here

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

4

16 回答 16

197

使用此方法:

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 "";
}

如何使用它:

string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
于 2012-05-22T20:43:14.890 回答
78

这是最简单的方法:

if(str.Contains("hello"))
于 2013-08-06T09:51:54.200 回答
29

您可以使用正则表达式:

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);
}
于 2012-05-22T20:47:54.043 回答
9
 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);
于 2012-05-22T20:42:58.930 回答
5

这是我使用 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;
}

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

用法是一样的:

string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
于 2016-09-09T13:26:21.720 回答
4

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

string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
于 2015-03-11T06:02:26.937 回答
4

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

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

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

无论如何,我已经将我的变体称为 - 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;
    }
}
于 2016-08-24T01:27:24.977 回答
3
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();
    }
于 2013-12-19T04:41:37.933 回答
3
  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);


        }
于 2016-09-02T01:17:09.017 回答
3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace oops3
{


    public class Demo
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the string");
            string x = Console.ReadLine();
            Console.WriteLine("enter the string to be searched");
            string SearchText = Console.ReadLine();
            string[] myarr = new string[30];
             myarr = x.Split(' ');
            int i = 0;
            foreach(string s in myarr)
            {
                i = i + 1;
                if (s==SearchText)
                {
                    Console.WriteLine("The string found at position:" + i);

                }

            }
            Console.ReadLine();
        }


    }












        }
于 2016-09-30T17:34:37.303 回答
2

这是替换字符串中部分文本的正确方法(基于 Oscar Jara 的 getBetween 方法):

public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
    {
        int Start, End, strSourceEnd;
        if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        {
            Start = strSource.IndexOf(strStart, 0) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            strSourceEnd = strSource.Length - 1;

            string strToReplace = strSource.Substring(Start, End - Start);
            string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
            return newString;
        }
        else
        {
            return string.Empty;
        }
    }

连接 3个string.Concat字符串:

  1. 找到要替换的字符串之前的字符串源部分 -strSource.Substring(0, Start)
  2. 替换字符串 -strReplace
  3. 找到要替换的字符串之后的字符串源部分 -strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
于 2018-12-20T17:47:29.737 回答
0

如果你知道你总是想要“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();
于 2012-05-22T20:45:52.703 回答
0

I have different approach on ReplaceTextBetween() function.

public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
        {
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
            {
                var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;

                var endIndex = strSource.IndexOf(strEnd, startIndex);

                var strSourceLength = strSource.Length;

                var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);

                var concatStart = startIndex + strToReplace.Length;

                var beforeReplaceStr = strSource.Substring(0, startIndex);

                var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);

                return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
            }

            return strSource;
        }
于 2021-02-08T05:42:52.530 回答
0

只需添加以下代码:

if (string.Contains("search_text")) { MessageBox.Show("Message."); }

于 2019-03-05T08:01:47.080 回答
0

先找文本的索引,再找子串

        var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");

        string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
于 2018-05-06T19:06:33.030 回答
0

在此处正确答案,无需使用任何预定义的方法。

    static void WordContainsInString()
    {
        int f = 0;
        Console.WriteLine("Input the string");
        string str = Console.ReadLine();
        Console.WriteLine("Input the word to search");
        string word = Console.ReadLine();
        int l = str.Length;
        int c = word.Length;

        for (int i = 0; i < l; i++)
        {
            if (str[i] == word[0])
            {
                for (int K = i + 1, j = 1; j < c; j++, K++)
                {
                    if (str[K] == word[j])
                    {
                        f++;
                    }
                    else 
                    { 
                        f = 0; 
                    }
                }
            }
        }
        if (f == c - 1)
        {
            Console.WriteLine("matching");
        }
        else
        {
            Console.WriteLine("not found");
        }
        Console.ReadLine();
    }
于 2021-07-13T22:30:57.140 回答