我正在研究如何用单词迭代一个字符串,从末尾开始,再到开头,一个字一个字地。
输出应如下所示:
我现在真的不知道从哪里/怎样开始。相反,我开始工作,但事实证明那不是我需要的(见下文)。
string descriptionText = "Column Grid Building"; //example
string[] description1TextArray = descriptionText.Split(' ');
int noItems = description1TextArray.Count();
for (int i = 0; i < noItems; i++)
{
if (i == 0)
{
search = search + description1TextArray[i];
}
else
{
search = search + " " + description1TextArray[i];
}
foreach (DataRow row in dt.Rows)
{
description1 = row[0].ToString();
abbreviation1 = row[1].ToString();
if (description1 == search || abbreviation1 == search)
{
comboBoxDescription1.SelectedIndex = comboBoxDescription1.FindStringExact(description1);
}
}
}
编辑:
很抱歉给你带来了混乱。
我从一个字符串“word1 word2 word3 word4”开始。我已经将每个单词设置为数组。
string[] description1TextArray = descriptionText.Split(' ');
int noItems = description1TextArray.Count();
我需要根据DataTable中的值检查字符串。例如,dataTable中的值是“Column Grid”。我的输入是“列网格构建”。
我需要从头到尾检查的原因是因为数据表中存在重叠的值,如“Column Grid”和“ColumnN”。当我从头到尾对字符串进行检查时,从未找到值“Column Grid”,因为已经在“Column”上找到了匹配项。
我希望这能更好地解释它。
您可以尝试以下操作:
using System.Linq;
string myString = "word1 word2 word3 word4";
var words = myString.Split(' ');
for ( int index = words.Length; index > 0 ; index-- )
{
string sentence = string.Join(" ", words.Take(index));
Console.WriteLine(sentence);
}
它是一个循环,通过向下计数索引器来获取所需的字数。
输出量
word1 word2 word3 word4
word1 word2 word3
word1 word2
word1
这样试试
string data = "word1 word2 word3 word4";
var strarray = data.Split(' ');
for ( int i = strarray.Length - 1; i >= 0; i-- )
{
Console.WriteLine(strarray[i]);
}
从字符串开始,将它拆分成数组,在循环中迭代它,每次迭代从数组长度中减去1。
string myString = "word1 word2 word3 word4";
string[] myArray = myString.Split(' ');
for (int i = myArray.Length - 1; i >= 0; i--)
{
Console.WriteLine(myArray[i]);
}