【问题标题】:Split a sentence using multiple characters?使用多个字符拆分一个句子?
【发布时间】:2017-08-28 05:44:21
【问题描述】:

我有一个输入框来输入句子,我想在每个特定字符处拆分它。我已经为. 做了这个:

 var ArraySourceTexts = textbox.Text.Split(new Char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

我的问题是,如果我有多个角色怎么办?例如,如果句子包含以下字符,我希望它拆分:.?!

请分享!

【问题讨论】:

  • 不确定是什么问题...您已经在使用数组重载 - 所以指定更多项目:new Char[] { '.' ,'?','!'}
  • 您的问题不清楚。你想达到什么目的?您能否提供示例和所需的输出?
  • 如果我有这样的例子:输入文本:这是一个例子。请检查,让我知道你的想法!所以我想从文本框中拆分句子,用“。”表示。和 ”,”。所以我希望输出有 3 个数组。 ` 1. 这是一个例子。 2. 请检查,3. 让我知道你的想法!`

标签: c# arrays split


【解决方案1】:

string.SplitChar 数组一起使用,您可以在该数组中指定任意数量的字符。只需添加更多会导致拆分的字符:

char[] splitChars = new char[] { '.', '!', '?', ',' };
var ArraySourceTexts = textbox.Text.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

输入:

this is an example. Please check, and let me know your thoughts!

输出:

[0] this is an example 
[1] Please check 
[2] and let me know your thoughts   

方法 2:如果您想拆分字符串但 保留 分隔符(就像您在 cmets 中提到的那样):

string[] arr = Regex.Split(textbox.Text, @"(?<=[.,!?])");

输入:

this is an example. Please check, and let me know your thoughts!

输出:

[0] this is an example.
[1] Please check, 
[2] and let me know your thoughts!   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多