Если я вас правильно понимаю, у вас есть строка, которая выглядит следующим образом:
"\r\n* lalalalalaal\r\n* 12121212121212\r\n* 36363636363636\r\n* 21454545454545454"
И вы хотите заменить "\r\n*"
на "\r\n1."
, где число 1
увеличивается каждый раз, когдаСтрока поиска найдена.
Если это так, вот один из способов сделать это: используйте метод IndexOf
, чтобы найти местоположение искомой строки, сохраняйте переменную-счетчик, которая увеличивается каждый раз, когда вы находите поисковый запрос, изатем используйте Substring
, чтобы получить подстроки до и после заменяемой части ('*'), а затем поместите значение счетчика между ними:
static string ReplaceWithIncrementingNumber(string input, string find, string partToReplace)
{
if (input == null || find == null ||
partToReplace == null || !find.Contains(partToReplace))
{
return input;
}
// Get the index of the first occurrence of our 'find' string
var index = input.IndexOf(find);
// Track the number of occurrences we've found, to use as a replacement string
var counter = 1;
while (index > -1)
{
// Get the leading string up to '*', add the counter, then add the trailing string
input = input.Substring(0, index) +
find.Replace(partToReplace, $"{counter++}.") +
input.Substring(index + find.Length);
// Find the next occurrence of our 'find' string
index = input.IndexOf(find, index + find.Length);
}
return input;
}
Вот пример с использованием вашей входной строки:
static void Main()
{
var input = "\r\n* lalalalalaal\r\n* 12121212121212\r\n* " +
"36363636363636\r\n* 21454545454545454";
Console.WriteLine(ReplaceWithIncrementingNumber(input, "\r\n*", "*"));
GetKeyFromUser("\nDone! Press any key to exit...");
}
Выход
![enter image description here](https://i.stack.imgur.com/SIwDt.png)