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

and I'd like to convert it to an int[] of 0 and 1:
Java
[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.
Java
int size = stringArray.length;
int [] arr = new int [size];
  for(int i=0; i<size; i++) {
	arr[i] =  Integer.parseInt(stringArray[i], 36) ;
}
Posted
Updated 21-Oct-20 23:16pm
v2
Comments
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.
[no name] 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

Try
Java
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]);
    System.out.println();
  }

  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
 
v2
Comments
ynjay 22-Oct-20 9:33am    
Thanks so much!
CPallini 22-Oct-20 9:37am    
You are welcome.
Something like:
Python
g = 'g'
e = 'e'
letters = [g, g, g, e, e, e, g, e, g, g]
bools = [x==g for x in letters]
print(bools)

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

Oops.
 
Share this answer
 
v2
Comments
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    
Doh!

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