需要查找包含條件的文本片段:需要從文本中查找最長的文本片段,其中的單詞以與前一個單詞的最後一個字母相同的字母開頭(例如:1. my 2年)。我需要打印出該片段以及他在文本中的行號。我的代碼:C#在文本中找不到正確的片段
public static string Longestfragment(string[] lines,char[] isolations ,ref int index)
{
string longestSentense = "";
int longestCount = 0;
int start = 0;
int end = 0;
foreach (string sentense in lines)
{
string[] words = sentense.Split(isolations); // split the words
int count = 0;
int line = 0;
line++;
for (int i = 0; i < words.Length - 1; i++)
{
// checking if the first word ends equals to the second word start
if (words[i].Equals("") || words[i + 1].Equals("")) continue; // checking if one of the words not empty.
if (words[i][words[i].Length - 1].Equals(words[i + 1][0]))
{
if (count == 0) //to find the start of fragment
{
start = sentense.IndexOf(words[i][0]);
end = sentense.IndexOf(words[i + 1][words[i + 1].Length - 1]);
}// to find the end of the fragment if the fragment if longer than 2 words.
if (count >= 1)
{
end = sentense.IndexOf(words[i + 1][words[i + 1].Length - 1]);
}
count++;
}
}
// if there is the longest fragment we save it.
if (count > longestCount)
{
longestCount = count;
longestSentense = sentense.Substring(start,end-1);
index = line; // to find the line index
}
}
return longestSentense; //returning the value of longestfragment
}
如果我的文本文件是:
大家好,我是山姆。我的歲月如此美好。
我得到的指數1(我想應該是0)和最長的句子(是薩姆。我多年的那麼好。)這是正確的。但是如果我的文本文件包含2行或更多行,如:
等於序列輸入繩八。
嗨,我叫薩姆。我的歲月如此美好。
我的程序只是崩潰或打印出錯誤的句子。請幫忙。
你能準確定義片段應該開始和結束的位置嗎?它是從第一次出現相同字母結尾和開頭的兩個單詞開始的嗎?它在哪裏結束?在行結尾?在下一個點'.'?那麼'你好,我叫薩姆。我的歲月如此美好。從來沒有更好。「這個片段在哪裏結束? –
@MongZhu它開始時,這兩個詞包含我說的條件。並在一個字母和另一個字母以不同的字母開頭時結束。 – Julius
因爲你在循環之前增加了'line',所以你得到index = 1。你如何處理標點符號? 'char [] isolation'的內容是什麼? –