Click here to Skip to main content
15,569,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a String[] that contains:
[g, g, g, e, e, e, g, e, g, g]

and I'd like to convert it to an int[] of 0 and 1:
[0, 0, 0, 1, 1, 1, 0, 1, 0, 0]

What I have tried:

I tried converting it to a radix base36 system but I'm not sure how to do it for 0 and 1.
int size = stringArray.length;
int [] arr = new int [size];
  for(int i=0; i<size; i++) {
	arr[i] =  Integer.parseInt(stringArray[i], 36) ;
Updated 22-Oct-20 0:16am
Sandeep Mewara 21-Oct-20 15:51pm    
What's the logic of alphabet to 1 or 0 here? What would happen if I give you any other letter here?
ynjay 21-Oct-20 16:24pm    
Basically I need a dataframe that uses labels of 0 and 1, which is based on an array it doesn't specifically matter which letters are used but must be only 2 letters and one has to be 0 and the other 1.
Gerry Schmitz 21-Oct-20 16:34pm    
Sounds like you're asking what "labels" to use ... How about Eggs and Spam.
ynjay 21-Oct-20 16:53pm    
I need an array of 0s and 1s

public class MyTest
  public static void main( String args[] )
    String [] sa = { "g", "g", "g", "e", "e", "e", "g", "e", "g", "g" };
    int [] ia = to_int(sa);
    for ( int i=0; i< ia.length; ++i)
      System.out.printf("%d, ", ia[i]);

  static int [] to_int(String sa[])
    int len = sa.length;
    int [] result = new int[len];

    for(int i = 0; i < len; ++i)
      result[i] = sa[i].equals("e") ? 1 : 0;
    return result;
Share this answer
ynjay 22-Oct-20 9:33am    
Thanks so much!
CPallini 22-Oct-20 9:37am    
You are welcome.
Something like:
g = 'g'
e = 'e'
letters = [g, g, g, e, e, e, g, e, g, g]
bools = [x==g for x in letters]

While that uses True and False as results, it should not be too difficult to get what you want.

Share this answer
CPallini 22-Oct-20 5:17am    
Hey Richard, I do know you like Python so much, but... It's Java!
Richard MacCutchan 22-Oct-20 5:33am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900