[英]how to get index of first letter of specific (n-th) word in sentence
我正在嘗試獲取句子中第 n 個單詞的第一個字母的索引。 這個詞可能在句子中重復了好幾次。
例如:我有句子bla blah bla bla bla
如何獲得第三個“bla”句子中第一個字母的索引?
int n=3
string[] words = richTextBox1.Text.Split(new Char[] { ' ' });//richTextBox1.Text="bla blah bla bla bla"
int index= richTextBox1.Text.IndexOf(words[n]);
但它返回第一個“bla”的索引,n=0
在我的示例中,它應該返回最后一個 bla 的索引,17
因為我不知道你從哪里得到你的字數值,所以我不得不做一些假設。 我構建了一個帶有 RichTextBox 的表單,一個用於報告索引的 TextBox,並向該表單添加了幾個常量。 我在代碼中記下了原因和一些替代方案。
我正在做的是遍歷數組並保留兩個索引值。 第一個索引值是我跳過的所有單詞(包括空格)的累加。 第二個索引值是我遇到目標詞的次數。 達到目標值后,我更新表單上的文本框並中斷。
public partial class Form1 : Form
{
const int WORDNUM = 3;
const char DELIMITER = ' ';
private void button1_Click(object sender, EventArgs e)
{
int cnt = 0; //How many times have I encountered the target word?
//int n = 3; I recommend you retrieve this value from a constant or form. This examples ignores this value and uses a constant.
int index = 0; //The accumulated index count of all words passed-over (including spaces).
//Here, I would also put your delimiter in a constant, or allow it to be configured by the user in the form.
string[] words = richTextBox1.Text.Split(DELIMITER); //richTextBox1.Text="bla blah bla bla bla"
for(int i = 0; i < words.Length; i++)
{
if (words[i] == WORD && cnt == NTHWORD)
{
textBox1.Text = index.ToString();
break;
}
else
{
index += words[i].Length + 1;
if(words[i] == WORD)
cnt++;
}
}
}
}
你的問題有點誤導。 你 state 你想要第三個“bla”中第一個字母的索引,這意味着你想要第四個單詞(@n = 3)的第一個字母的索引。 你也 state 你應該得到 17 這與前面的陳述相矛盾。 如果 n = 3,答案應該是 13。試試這個:
string sentence = "bla blah bla bla bla";
string sentence2 = "The quick brown fox jumped over the lazy dog";
int n = 3; //The fourth word: bla, will return 13
int n2 = 6; //The seventh word: the, will return 32
Console.WriteLine($"{sentence}, n = {n}:\t {GetIndexOfFirstLetterInNthWord(n, sentence)}");
Console.WriteLine($"{sentence}, n = {n}:\t {GetIndexOfFirstLetterInNthWord(n2, sentence2)}");
//@ n = 3, we choose the fourth word, index of first letter == 14
int GetIndexOfFirstLetterInNthWord(int index, string sentence)
{
int retVal = -1;
string[] splitSentence = sentence.Split(' ');
if (index < splitSentence.Length)
{
retVal = 0;
for (int i = 0; i < index; i++)
{
retVal += splitSentence[i].Length + 1;
}
}
return retVal;
string sentence = "bla blah bla bla bla"; // <- your TextBox
string[] words = sentence.Split(new Char[] { ' ' });
int n = 3;
var wordToSearch = words[n] + " ";
Dictionary<int, string> indexesByWord = new Dictionary<int, string>();
MatchCollection matches = Regex.Matches(sentence, wordToSearch);
for (int i = 0; i < words.Count(); i++)
{
if (words[i].Equals(words[n]))
{
indexesByWord.Add(i, wordToSearch);
}
}
int countDuplicateWordsBeforeN = 0;
foreach(var i in indexesByWord)
{
if(i.Key < n)
{
countDuplicateWordsBeforeN++;
}
}
var index = matches[countDuplicateWordsBeforeN].Index;
未經測試,希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.