加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用特定条件将字符串拆分为多个字符串

发布时间:2020-12-15 23:41:43 所属栏目:百科 来源:网络整理
导读:我想根据以下条件将字符串拆分为多个字符串: 它必须至少2个单词 每个单词必须彼此相邻 例如: “你好,你好吗”我想分成: “你好,你好吗” “你好,怎么样” “你好怎么样” “怎么样” “你好吗” “你呢” 不能重复多次. 到目前为止我得到的是: string in
我想根据以下条件将字符串拆分为多个字符串:

>它必须至少2个单词
>每个单词必须彼此相邻

例如:
“你好,你好吗”我想分成:

>“你好,你好吗”
>“你好,怎么样”
>“你好怎么样”
>“怎么样”
>“你好吗”
>“你呢”

不能重复多次.

到目前为止我得到的是:

string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();

string temp = String.Empty;

for (int i = 0; i < words.Count; i++)
{
    temp += words[i] + " ";
    if (i > 0)
    {
        inputs.Add(temp);
    }
}

它输出以下内容:

hello how 
hello how are 
hello how are you

我也希望得到其他人,并需要一些帮助.

解决方法

一种方法是迭代每个单词并获得所有可能的序列.

例:

string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();

for (int i = 0; i < words.Count; i++)
{
    var temp = words[i];
    for(int j = i+1;j < words.Count;j++) {
        temp += " " + words[j];
        inputs.Add(temp);
    }
}
//hello how 
//hello how are 
//hello how are you 
//how are 
//how are you 
//are you

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读