-1

对不起,这对我来说有点难以解释。

我想获取在应用程序中放置在不同字符之前的最后一个换行符C#的索引。

例如,我想要\n放置在前面的索引Hi

"\n\n\n\n\nHi\n\n\n"

我也想要它的第一个索引\n放在Hi.

我知道String.LastIndexOf有多种使用方法。我只是不知道我是否可以或如何使用它来获得我想要的东西。

编辑

这就是我到目前为止所想到的。

int firstIndex=myString.IndexOf("\n")==0 ? 0 : -1;
int secondIndex=myString.Text.Trim().IndexOf("\n");

我想知道是否有更好或更标准的方法来做到这一点。

4

3 回答 3

1

您可以使用 Regex.Matches 查找具有模式的项目。一个简单的方法可以是

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var input = "\n\nHi\n\n\nTest\nTest";

        var matches = Regex.Matches(input, "\\n");

        for (int index = 0; index < matches.Count - 1; index++)
        {
            var match = matches[index];

            if (match.Index + 1 != matches[index + 1].Index)
            {
                Console.WriteLine("Last Match found at " + match.Index);
                Console.WriteLine("Next first Match found after last item at " + matches[index + 1].Index);
            }
        }

        Console.WriteLine("Last Match found at " + matches[matches.Count - 1].Index);
    }
}

它将输出打印为

Last Match found at 1
Next first Match found after last item at 4
Last Match found at 6
Next first Match found after last item at 11
Last Match found at 11
于 2015-11-22T06:30:05.770 回答
0

有很多方法可以剥这只猫的皮。这是一个

string input = "\n\n\n\n\nHi\n\n\n";
string [] split = input.Split('\n');
int prevN = -1, nextN = -1;
for (int i = 0; i < split.Length; i++) {
     if (!String.IsNullOrEmpty(split[i])) {
        prevN = i - 1;
        nextN = i + split[i].Length;
        break;
    }
}
Console.WriteLine(prevN + "-" + nextN);

打印“4-7”。那是对的吗?

于 2015-11-22T06:16:21.087 回答
0

您可以尝试以下方法

static void Main(string[] args)
{
    int index = "\n\n\n\n\nHi\n\n\n".IndexOf("hi", StringComparison.OrdinalIgnoreCase);
    Console.WriteLine("\n\n\n\n\nHi\n\n\n".Split('i')[1].IndexOf("\n") + index);
    Console.WriteLine("\n\n\n\n\nHi\n\n\n".Split('i')[1].LastIndexOf("\n") + index);
}
于 2015-11-22T06:24:36.050 回答