So I have a script where the user can type certain things in a text box and press enter to trigger the system to say something back, like an AI. The problem is, I have to type every possible thing a person can say with each form of grammer someone could use, such as with this line.
Is there an easier way to check if a person types “hello” where all forms of the grammar apply? Such as with caps or no caps? I hate having to write it every way a person could spell it.
Use string.ToLower to compare strings vs a set of lower case strings. This will create a new string when you do the conversion.
Or you can use a case insensitive string comparison with string.Compare.
To check if a string matches any of a set of strings, case insensitive, without allocating a new string object, you can do something like this using StringComparer.OrdinalIgnoreCase:
using UnityEngine;
using System; // "StringComparerer" type
using System.Linq; // "Contains" extension method
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
Respond("HELLO");
Respond("SeeYa");
Respond("Foosballz");
Respond("heLLo");
}
void Respond(string input)
{
if (Synonyms.Hi(input))
print("Hello to you too!");
else if (Synonyms.Bye(input))
print("Nice seeing you!");
else
print("What you are on about?");
}
}
public static class Synonyms
{
static string[] hi = { "Hello", "Hey", "Hi" };
static string[] bye = { "Bye", "Seeya", "Good bye" };
static StringComparer anyCase = StringComparer.OrdinalIgnoreCase;
public static bool Hi(string input)
{
// "Contains" test if input exist in hi, using anyCase
return hi.Contains(input, anyCase);
}
public static bool Bye(string input)
{
// "Contains" test if input exist in bye, using anyCase
return bye.Contains(input, anyCase);
}
}