[英]Split every two words from string using 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();
}
此代碼返回輸出像
一種
b
C
d
Ë
F
G
H
我想像這樣每兩個字分開
AB
公元前
光盤
德
EF
FG
GH
您必須將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]}";
}
如果我們有“ abc”,它將顯示
a b
b c
如果我們有“ abcd”
a b
b c
c d
最好的方法是使用正則Regex
(正則表達式):
foreach(var s in (new System.Text.RegularExpressions.Regex(@"[^ ]+ [^ ]+")).Matches("a b c d e f"))
TextBox1.Text += s.ToString()+"\n";
您可以在這里看到結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.