user238384
user238384

Reputation: 2466

small java problem

Sorry if my question sounds dumb. But some time small things create big problem for you and take your whole time to solve it. But thanks to stackoverflow where i can get GURU advices. :)

So here is my problem. i search for a word in a string and put 0 where that word occur. For example : search word is DOG and i have string "never ever let dog bite you" so the string would be 000100 . Now when I try to convert this string into INT it produce result 100 :( which is bad. I also can not use int array i can only use string as i am concatinating it, also using somewhere else too in program.

Now i am sure you are wondering why i want to convert it into INT. So here my answer. I am using 3 words from each string to make this kind of binary string. So lets say i used three search queries like ( dog, dog, ever ) so all three strings would be 000100 000100 010000 Then I want to SUM them it should produce result like this "010200" while it produce result "10200" which is wrong. :(

Thanks in advance

Upvotes: 0

Views: 225

Answers (4)

rayd09
rayd09

Reputation: 1897

You could prefix your value with a '1', that would preserve your leading 0's. You can then take that prefix into account you do your sum in the end.

That all is assuming you work through your 10 overflow issue that was mentioned in another comment.

Upvotes: 1

mr-sk
mr-sk

Reputation: 13417

Could you store it as a character array instead? Your using an int, which is fine, but your really not wanting an int - you want each position in the int to represent words in a string, and you turn them on or off (1 or 0). Seems like storing them in a character array would make more sense.

Upvotes: 0

akf
akf

Reputation: 39495

Looks like you might want to investigate java.util.BitSet.

Upvotes: 3

danben
danben

Reputation: 83310

Of course the int representation won't retain leading zeros. But you can easily convert back to a String after summing and pad the zeros on the left yourself - just store the maximum length of any string (assuming they can have different lengths). Or if you wanted to get even fancier you could use NumberFormat, but you might find this to be overkill for your needs.

Also, be careful - you will get some unexpected results with this code if any word appears in 10 or more strings.

Upvotes: 6

Related Questions