【问题标题】:how to get string in stringcontains c# in unity?如何在字符串中统一获取包含 c# 的字符串?
【发布时间】:2020-11-21 02:36:47
【问题描述】:

我可以从包含的字符串中获取字符串吗?当我输入“asdsahello1”时,如何在列表中获取字符串,只有“hello1”包含字符串。

public class FindContainsText : MonoBehaviour
{
private string[] test = { "hello1", "hello2" };
public Inputfield inputText;

void Update()
{
  foreach (string x in test)
    {
       if(inputText.Contains(x))
        {
        string getString;
        getString=//inputText.Contains(x) how?
        }
    }
}
}

【问题讨论】:

  • 您可以在此处使用for( int i=0 ; i<array.Length ) 循环。给定if(true) break;i 将是您要查找的索引
  • 应该是inputText.Contains(x)而不是inputText.Contains.x

标签: c# arrays string list unity3d


【解决方案1】:

试试这个代码 sn-p:

public class FindContainsText : MonoBehaviour
{
    private string[] test = { "hello1", "hello2" };
    public InputField inputText;

    public void Update()
    {
        int matchIndex = -1;
        for (int i = 0; i < test.Length; i++)
        {
            if (inputText.text.Contains(test[i]))
            {
                matchIndex = i;
                break;
            }
        }

        if (matchIndex != -1)
        {
            Debug.Log($"Input field contains {test[matchIndex]} (element number {matchIndex})");
        }
        else
        {
            Debug.Log("No match!");
        }
    }
}

还可以考虑使用onValueChanged 事件而不是更新。每次更新 Inputfield 时都会调用它。

【讨论】:

    【解决方案2】:
    getString=x;
    

    变量 x 包含您正在测试的值。

    【讨论】:

    • x = hello1 和 hello2
    • 是的,您的字符串可以包含您的一些测试字符串,例如“asdsahello1asdasdsahello2”。你可以得到所有的比赛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2021-12-23
    • 2020-08-26
    相关资源
    最近更新 更多