C#/ASP.Net 中使用分隔符分割字符串

发布于 2024-12-01 09:46:44 字数 163 浏览 0 评论 0原文

如果我这样做:

 string text = "Hello, how are you?";

 string[] split = text.Split('h', 'o');

如何获取每个拆分之间使用的分隔符的列表?我正在尝试重新创建整个字符串。

If I do this:

 string text = "Hello, how are you?";

 string[] split = text.Split('h', 'o');

How do I get a list of what delimiter was used between each split? I'm trying to recreate the string as a whole.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白芷 2024-12-08 09:46:44

正如@Davy8 提到的,没有内置的方式。这是一个非常简单的示例,可帮助您继续编写自定义方法。

void Main()
{
    string text = "Hello, how are you?";
    List<SplitDefinition> splitDefinitionList = CustomSplit(text, new char[] { 'h', 'o' });
}

public List<SplitDefinition> CustomSplit(string source, char[] delimiters)
{
    List<SplitDefinition> splitDefinitionList = new List<SplitDefinition>();

    foreach(char d in delimiters)
    {
        SplitDefinition sd = new SplitDefinition(d, source.Split(d));           
        splitDefinitionList.Add(sd);
    }

    return splitDefinitionList;
}

public class SplitDefinition
{
    public SplitDefinition(char delimiter, string[] splits)
    {
        this.delimiter = delimiter;
        this.splits = splits;
    }

    public char delimiter { get; set; }
    public string[] splits { get; set; }
}

As @Davy8 mentioned, there is no built in way. Here's a VERY simple example to get you going on writing a custom method.

void Main()
{
    string text = "Hello, how are you?";
    List<SplitDefinition> splitDefinitionList = CustomSplit(text, new char[] { 'h', 'o' });
}

public List<SplitDefinition> CustomSplit(string source, char[] delimiters)
{
    List<SplitDefinition> splitDefinitionList = new List<SplitDefinition>();

    foreach(char d in delimiters)
    {
        SplitDefinition sd = new SplitDefinition(d, source.Split(d));           
        splitDefinitionList.Add(sd);
    }

    return splitDefinitionList;
}

public class SplitDefinition
{
    public SplitDefinition(char delimiter, string[] splits)
    {
        this.delimiter = delimiter;
        this.splits = splits;
    }

    public char delimiter { get; set; }
    public string[] splits { get; set; }
}
傲鸠 2024-12-08 09:46:44

据我所知,没有内置的方式。您最好编写自己的自定义拆分方法来跟踪分隔符。

There isn't a built in way that I'm aware of. You're probably better off writing your own custom split method that keeps track of the delimiters.

柏林苍穹下 2024-12-08 09:46:44

这是不可能的。字符串已被拆分,那么您如何知道拆分是基于“h”还是“o”?

无论如何,如果你能做到这一点:

 string[] split = text.Split('h', 'o');

那么为什么不存储这些字符呢?

This is impossible. The string has been split, so how can you possibly know if the split was based on a 'h' or an 'o'?

Anyways if you can do this:

 string[] split = text.Split('h', 'o');

then why not also store those characters?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文