Найти текст в строке с С#
Как я могу найти данный текст внутри строки? После этого я хотел бы создать новую строку между этим и другим. Например...
Если строка была:
This is an example string and my data is here
И я хочу создать строку с тем, что находится между "моим" и "есть", как я могу это сделать? Извините, это довольно псевдо, но, надеюсь, это имеет смысл.
Ответы
Ответ 1
Используйте эту функцию.
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
Как использовать его:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
Ответ 2
Это самый простой способ:
if(str.Contains("hello"))
Ответ 3
Вы можете использовать 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);
}
Ответ 4
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);
Ответ 5
Вы можете сделать это компактно следующим образом:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Ответ 6
За исключением ответа @Prashant, на приведенные выше ответы ответили неправильно. Где функция "заменить" ответа? ОП спросил: "После этого я хотел бы создать новую строку между этим и чем-то другим".
Основываясь на превосходном ответе @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;
}
}
Ответ 7
Здесь моя функция, использующая функцию 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");
Ответ 8
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();
}
Ответ 9
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);
}
Ответ 10
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();
}
}
}
Ответ 11
Если вы знаете, что всегда хотите, чтобы строка между "моими" и "есть", вы всегда можете выполнить следующее:
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 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();
Ответ 12
Сначала найдите индекс текста, а затем подстроку
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
Ответ 13
Это правильный способ заменить часть текста внутри строки (на основе метода 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;
}
}
string.Concat
объединяет 3 строки:
- Часть источника строки перед найденной
strSource.Substring(0, Start)
- strSource.Substring(0, Start)
-
strReplace
строка - strReplace
- Часть источника строки после найденной строки -
strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)