- Home /
 
[JS] How convert a String[] to int[]
Hello
I extract data from a text file with "fileContents.Split()" into a String[] variable
But the values are only integers, I'd like to stock them into an integer Array int[]
 var sr = new StreamReader("Assets/tilemap_layer_1.txt");
 var fileContents = sr.ReadToEnd();
 sr.Close();
      
 tileMap = fileContents.Split(","[0]);
 
               If I declare tileMap like this : "var tileMap : int[];" it doesn't work, I get "BCE0022: Cannot convert 'String[]' to 'int[]'."
How I could convert tileMap into an integer array ? Is it possible ? String array is too slow
Thank you
Answer by JPB18 · Dec 22, 2013 at 04:02 PM
Well, first of all, I'd recomend you used data collections like Lists for that. They're generics, so you'll have to import them into your script. So lets do something like this:
 import System.Collections.Generic;
 
 function readFile() : List.<int> {
     //first read the contents
     var sr = new StreamReader("Assets/tilemap_layer_1.txt");
     var fileContents = sr.ReadToEnd();
     sr.Close();
 
     //split it
     var tileMap : String[] = fileContents.Split(","[0]);
 
     //now we create our List
     var mapList : List.<int> = new List.<int>();
 
     //now we cycle through the entire content of tileMap
     for(var ctt : String in tileMap) {
        mapList.Add(ctt.ToInt32()); //don't forget to convert the string to int
     }
 
     return mapList; //return content
 
 }
 
               And there you go! (Note, I wrote the code directly here, so it might have some errors).
Awesome !
Thank you very much it works very well :)
I just had to change mapList.Add(ctt.ToInt32()); to mapList.Add(int.Parse(ctt)); I hope it works as fast
You're welcome! Ps: don't forget to check this as an answer, by ticking the button under the like/dislike widget :P
Your answer
 
             Follow this Question
Related Questions
Javascript int to float 1 Answer
How to make this line work in C#? 1 Answer
Convert int to string and back again 2 Answers
Convert Text to float 3 Answers
Mob Spawner, choosing a random mob 2 Answers