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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Convert a string to array, so I can replace every character

Discussion in 'Scripting' started by Fabian_G, Oct 31, 2022.

  1. Fabian_G

    Fabian_G

    Unity Technologies

    Joined:
    May 14, 2019
    Posts:
    2
    Hi there team!

    I am trying to find a solution for this with no luck.

    What I am asked to do is to replace every letter from the string "anilina" by it's middle character which is L. So the results gets to be "LLLLLLL", instead of the initial word.

    How can I detect that L in the middle of the string? Thanks!
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    Seems like an interview question, but I'll bite. You can just treat the string as an Array of characters. Just get the length, divide it by 2, and that should be the middle character's index.
     
    Fabian_G likes this.
  3. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    String length divided by two

    And should be something near on

    new string . character replace


    But you could for loop that and say if we are not the middle then make me the middle.
     
    Fabian_G likes this.
  4. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Code (CSharp):
    1.  
    2.         string RESULT = "";
    3.         int I = ANILINA.Length / 2;
    4.         char KEYCHARACTER = ANILINA[I];
    5.         for (int i = 0; i < ANILINA.Length; i++)
    6.         {
    7.             if (ANILINA[i] != KEYCHARACTER && i == I)
    8.             {
    9.                 RESULT += ANILINA[i];
    10.             }
    11.             else
    12.                 RESULT += KEYCHARACTER;
    13.         }
    14.         Debug.Log(RESULT);
    15.  
     
    Fabian_G likes this.
  5. Fabian_G

    Fabian_G

    Unity Technologies

    Joined:
    May 14, 2019
    Posts:
    2
    Thanks! It worked! It was not for an interview but a challenge that was left to us in a C# class haha, thanks <3
     
    AnimalMan likes this.
  6. AnimalMan

    AnimalMan

    Joined:
    Apr 1, 2018
    Posts:
    1,164
    Not a problem