Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Find a letter in string using indexOf?

Discussion in 'Scripting' started by MindGem, Jan 17, 2018.

  1. MindGem

    MindGem

    Joined:
    May 11, 2017
    Posts:
    84
    Hi.

    I have an input field. say you type in your name. "mike"
    I want to have an array or list and push in the name character by character.

    So can I use something like stringName.indexOf("2");
    and get "k"?

    Or whats the best way to break the name down in individual characters?
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    This ought to work:
    Code (CSharp):
    1.  
    2. string name = "What ever";
    3. List<char> characters = new List<char>();
    4.  
    5. for(int i = 0; i < name.Length; i++) {
    6.   characters.Add(name[i]);
    7. }
    8.  
     
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,419
    A string can be accessed like an array. E.g. "mike"[2] returns 'k'.
     
    jaydenshi99 and TaleOf4Gamers like this.
  4. MindGem

    MindGem

    Joined:
    May 11, 2017
    Posts:
    84
    Thank you PGJ,

    I had something very close to that but thx for sorting it out for me.
     
  5. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    This, no need to over-complicate it
     
    Peter77 likes this.
  6. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    There's also the 'ToCharArray' method. It'll return the string as an array of characters.

    Code (csharp):
    1. Char[] chars = "Unity".ToCharArray();
     
    TaleOf4Gamers and PGJ like this.