Can I check a specific character in a string?

I’m trying to check letter by letter in a string.

I have an InputField and I want to for loop it checking what each char is.

for(length)
switch(i)
if(word.text.indexOf(i)) == “a”;
Debug.Log(“A”);

and so on.

How do I go about doing that. I run into problems with checking the indexOf with type conversions.

Both of these work:

string s = "Hello World";
for(int i = 0; i < s.Length; i++)
{
    char c = s[i];
    Debug.Log(c);
}

foreach(char c in s)
{
    Debug.Log(c);
}
1 Like

The code is not making sense to me. :slight_smile:

Do you want to find a specific character or do you literally want to check every character?

Lordofduct Thank you! thats all I needed.

methos, I was trying to write pseudo code to explain it better, I know it’s not real syntax :slight_smile:

Fair enough.

The second part of my post was asking if you wanted to find a specific character, or scan each one – maybe doing something unique for each or several. For instance, if you only wanted to know if 1 character was in the text, indexOf is probably faster. Regardless, though… glad you got your solution :slight_smile:

2 Likes

I do have a followup question.

So in my test I just want to write out sprites with letters to see if it works.
for (int i = 0; i < word.text.Length; i++)
{
char letterAtPosition = word.text ;
switch(letterAtPosition)
{
case ‘a’:
GameObject letterChild = Instantiate (letter [0], new Vector2 (0, 0), Quaternion.identity);
letterChild.transform.SetParent (GameObject.FindGameObjectWithTag (“canvas”).transform, false);
break;
So this works…but my only idea is to put 26 cases for all my A-Z letters. Is there a way I can replace the index of 0 in this case so I only have to do One line of code?

Oh and also…instead of new GameObects… can I replace that line to have the same. maybe pre-make a list of gameobejcts?

Use code tags:
Using code tags properly page-2#post-3353071

Also… lower-case letter a is int 97, and they climb incrementally to z = 122. This means if you convert the char to an int and subtract 97, you’ll get a int from 0-25. The 26 indices of your array.

char letter = word.text[i];
if(!char.IsLetter(letter)) continue; //someone typed in a none letter, skip to the next letter in the loop
int index = (int)char.ToLower(letter) - 97; //ensure you tolower incase someone typed in upper-case

You could keep a pool of game objects and swap the sprite as needed. That might help a little bit. Make a pool of sufficient size to start, and only grow it if needed :slight_smile:

Thx guys. I’ll reseach what you said.