[英]Foreach loop iteration error
因此,我需要運行一個或多個循環來替換出現在allSentencesList中的句子中的EntityList中存在的某些單詞,然后將帶有替換單詞的新句子添加到processedSentencesList中。 但是該操作無法如我所願。 知道錯誤可能是什么嗎?
碼:
private void button1_Click(object sender, EventArgs e)
{
List<string> allSentencesList = new List<string>(new String[]
{"Cat jumped over the Wall", "Car was parked", "Car crashed" ,
"Cat walked on the wall"});
List<string> processedSentencesList = new List<string>();
List<string> entityList = new List<string>(new string[]
{ "Cat", "Car", "Wall" });
foreach (string sentence in allSentencesList)
{
foreach (string entity in entityList)
{
string processedString = sentence.Replace(entity,
(entity + "/" + "TYPE"));
processedSentencesList.Add(processedString);
}
}
foreach (string sen in processedSentencesList)
{
testBox.Items.Add(sen);
Console.WriteLine(sen);
}
}
這是我要顯示的
Cat/TYPE jumped over the Wall/TYPE
Car/TYPE was parked
Car/TYPE crashed
Cat/TYPE walked on the wall/TYPE
這就是顯示的內容
Cat/TYPE jumped over the Wall
Cat jumped over the Wall
Cat jumped over the Wall/TYPE
Car was parked
Car/TYPE was parked
Car was parked
Car crashed
Car/TYPE crashed
Car crashed
Cat/TYPE walked on the Wall
Cat walked on the Wall
Cat walked on the Wall
看起來您是在內部foreach循環中多次添加到“已處理”列表中。
完成所有要在字符串中進行的替換后,您只需一次將其添加到進程列表中。 使您的代碼盡可能接近原始代碼,請嘗試以下操作:
foreach (string sentence in allSentencesList)
{
string processedString = sentence;
foreach (string entity in entityList)
processedString = processedString.Replace(entity, (entity + "/" + "TYPE"));
processedSentencesList.Add(processedString);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.