首页 > 解决方案 > 使用asp.net c#从字符串中拆分每两个单词

问题描述

我可以使用以下代码从字符串中拆分每个单词:

string s = TextBox1.Text.Trim().ToString(); // a b c d e f g h 
string[] words = s.Split(' ');
foreach (string word in words)
{
    TextBox1.Text += "\n"+word.ToString();
}

此代码返回输出,如
a
b
c
d
e
f
g
h

我想像这样拆分每两个单词

ab
bc
cd
de
ef
fg
gh

标签: c#asp.net

解决方案


您必须将 foreach 转换为 for 循环并使用索引

string s = TextBox1.Text.Trim().ToString(); //a b c d e f g h 
string[] words = s.Split(' ');
for (int i = 0; i < words.Length - 1; i++)
{
    TextBox1.Text += $"\n{words[i]} {words[i + 1]}";
}

如果我们有“ab c”,它将显示

a b
b c

如果我们有“abc d”

a b
b c
c d

推荐阅读