Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes String question! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String question!" Watch "String question!" New topic
Author

String question!

zoster gibrilian
Greenhorn

Joined: Sep 17, 2003
Posts: 7
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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 .


[Jess in Action][AskingGoodQuestions]
MSanjeevMehra
Greenhorn

Joined: Sep 18, 2003
Posts: 17
----------------------------------------------------------------------------
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 ]

Wish U Happiness,<br />Sanjeev.
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
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!


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: String question!
 
Similar Threads
amount currency datatype
Looking for correct data type to take in stream of xml
Please Comment on Data Section
how to sovle these two errors~~~help~~~
SQL Data Types