如何在单击或点击时返回文本中单词的编号



如何在点击或点击时返回文本中的单词编号?

我正在考虑使用Find.HitHighlight Method (Word) - MSDN(或类似的东西),但我不知道如何。现在,我可以计算我拥有的文本中的单词并将它们存储在集合中,但是我现在如何知道单击或录制了哪个单词,以便它可以返回集合中该单词的数量并突出显示它。

多谢!

以下是字数统计的代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions;
public class WordCount : MonoBehaviour {
public Text textToCount;
// Use this for initialization
void Start () {
    Debug.Log(CountWords1(textToCount.text));
}
// Update is called once per frame
void Update () {
}
public static int CountWords1(string s)
{
    MatchCollection collection = Regex.Matches(s, @"[S]+");
    return collection.Count;
    }
}

你应该做的是使用字典,其中每个单词都是键值。

public Dictionary<string, int> AnalyzeString(string str)
{
    Dictionary<string,int> contents = Dictionary<string,int>();
    string[] words = str.Split(' ');
    foreach(string word in words)
    {
        if(contents.ContainsKey(word))
        {
            contents[word]+=1;
        }
        else
        {
            contents.Add(word,1);
        }
    }
    return contents;
}

有了这个,您现在可以看到查询的单词在字符串中的次数。只是通过做

int numberOfTimes = 0;
if(contents.ContainsKey("yourDesiredWord"))
    numberOfTimes = contents["yourDesiredWord"];

最新更新