• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String question!

 
zoster gibrilian
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i have the following string:
string binary = "10000010111101010001101100000010";
How can i verify that the string is made up of only 0 and 1's?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, one way would be to loop over the characters and check each one:

Another approach, useful in only specific situations, would be to use the Integer.parseInt(String, int) method, specifying base 2; this method will return the binary value as an int if it can, or otherwise throw a NumberFormatException. This would be useful if you were sure the value would always be less that Integer.MAX_VALUE .
 
MSanjeevMehra
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
----------------------------------------------------------------------------
string binary = "10000010111101010001101100000010";
----------------------------------------------------------------------------
needs JDK1.4 for matches("") method.
binary.matches("01"); returns true if binary contains 0 or/and 1; else false.
[ September 22, 2003: Message edited by: MSanjeevMehra ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The previously suggested solution won't work quite as desired. It will match only the String "01" and will result in false in the example input String.
Allow me to suggest a slight modification that should work well.
----
Also MSanjeevMehra,
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic