wood burning stoves 2.0
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String question!" Watch "String question!" New topic

String question!

zoster gibrilian

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

Joined: Jul 08, 2003
Posts: 24199

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]

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

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]
I agree. Here's the link: http://aspose.com/file-tools
subject: String question!
It's not a secret anymore!