Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes String length without using String.length() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String length without using String.length() method" Watch "String length without using String.length() method" New topic
Author

String length without using String.length() method

Monish Kaushal
Greenhorn

Joined: Dec 12, 2010
Posts: 9
Hi , Anyone can give me the program to find the length of the string without using any built in length methods or length properties.

Thank you

sdwork
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8705
    
    6

Please do not post the same question in multiple forums. It causes duplication of effort as the community tries to help everyone.
CarefullyChooseOneForum
Also, check your private messages for an important administrative issue.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3366
    
    9
Why would you want this?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

You can't. Period. It's like me asking for your name and you're not allowed to give me your name directly, on paper or anything.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8705
    
    6

I have an idea that may work, but it depends exactly on what the constraints on the answer are. Is this a homework question that the user is supposed to solve? Exactly how is the question worded so I know if my answer is applicable.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

With "normal" Java you can't. But with reflection you can:



But then again, why would you want this?


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Reflection doesn't count, that's still querying the property. toCharArray().length also doesn't count because that's calling the property indirectly. As is toString().length(). Adding the String to a StringBuilder calls length() on the String, so again no-go.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Wouter Oet wrote:With "normal" Java you can't. But with reflection you can:



But then again, why would you want this?

I hate to burst your bubble but the char[] value can be larger than the actual String. When substring is called it the substring will share the same char[]. You can see this by declaring s as "asdf".substring(2). It's the count field that you need.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3165
    
  10
You could write a loop to call charAt method until you get an out of bounds exception.


Joanne
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8705
    
    6

Joanne Neal wrote:You could write a loop to call charAt method until you get an out of bounds exception.


That's the direction I was heading, but I didn't want to give it away unless this was homework. . .
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3165
    
  10
Joe Ess wrote:That's the direction I was heading, but I didn't want to give it away unless this was homework. . .


That's fair enough, but I thought Rob's post
Rob Prime wrote:You can't. Period.
might have been a little discouraging, so I thought I'd give him a nudge in a possible direction.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Ah right. I never think of these nasty ways. Using exceptions for control flow is just bad. I still hate Sun for not giving us a way for testing if a String can be parsed into an int / long / ... without actually trying the parsing and catching NumberFormatException.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3165
    
  10
Rob Prime wrote:Using exceptions for control flow is just bad.
I agree, but when you get these sort of requirements, sometimes you have to turn to the dark side.
Monish Kaushal
Greenhorn

Joined: Dec 12, 2010
Posts: 9
Dear all, This was a question asked at the Interview. I tried converting the string into array, StringBuffer. But was of no use.

And regarding post by Joanne Neal, we can loop using charAt until we get OutofBound exception. But it is a runtime exception.
Is it a good practice to catch the Runtime Exceptions and handle them?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Definitely not, but I do feel that this is the answer the interviewer was looking for. I doubt they would want to see it in your code though.

And you were asked before, by Joe, to check your private messages. And by Paul Sturrock before that. So please do so now.
Jan Hoppmann
Ranch Hand

Joined: Jul 19, 2010
Posts: 142

Rob Prime wrote:Ah right. I never think of these nasty ways. Using exceptions for control flow is just bad.


You could always just cast the String to lower case, add an "A" to the end and then call indexOf, that would give you the length and no exception


Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Quite inventive indeed!
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1665
    
    7

Except technically that would be the length of a entirely different String object, being that String's are immutable so you can't actually append to any given instance


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

It would still be the length of the original String. indexOf would return the index of the A character which is at the end of the original String. Therefore, the index of the A in the modified String is equal to the size of the original String.
Monish Kaushal
Greenhorn

Joined: Dec 12, 2010
Posts: 9
@Jan Hoppmann, really nice idea. Thanks a lot for the solution. Thanks to all who posted on this thread. Thanks for your time and interest in solving this problem.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

You do understand that all of these solutions are purely academic? There is one, and only one, solution you should ever use in production code: call the length() method.
Monish Kaushal
Greenhorn

Joined: Dec 12, 2010
Posts: 9
Yes Rob, in the production the best practice is to use available APIs. But still these kind of cheeky questions will arise in the interviews which are unavoidable. Anyhow, I even tried checking the actual API implementation of length() method which just returns private count of String object.

My first thought was to convert the string to StringBuilder or to char array and find the length. Even then to traverse the array till last element we need length!. So dropped them. At one time I thought of appending some marker character to the end of StringBuilder or array and manipulating. Still, what if the same marker character used in the program is the last character in the given string! Doing the case conversion and then appending the marker character never flashed in my mind.

Anyways, I have found myself a gem by finding coderanch
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1665
    
    7

Rob Prime wrote:It would still be the length of the original String. indexOf would return the index of the A character which is at the end of the original String. Therefore, the index of the A in the modified String is equal to the size of the original String.


I know, but I still think it's cheating
Jan Hoppmann
Ranch Hand

Joined: Jul 19, 2010
Posts: 142

Jelle Klap wrote:I know, but I still think it's cheating


But it solves the problem ;)
Santosh Kumar Nayak
Ranch Hand

Joined: Aug 02, 2011
Posts: 81
Try using character Array. You can calculate the size.
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 865
    
    5
1) check whether the given string equals("") and if yes, it is of zero length.
Otherwise let n := 1
2) Make a cycle listing all possible strings of the length "n"
and check whether the given string equals to one of then.
If yes, it is of length "n"
Otherwise let n := n + 1 and go to 2)

This "solution" not only avoids the usage of length() on strings, stringbuffers etc. but it is also very inefficient.,
which contributes to the fun. Fun is the major (if not only) benefit to be hoped from the exercise.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7029
    
  16

Ivan Jozsef Balazs wrote:This "solution" not only avoids the usage of length() on strings, stringbuffers etc. but it is also very inefficient...

Actually, not as bad as you might think, because you can re-use the code to create a brute-force password cracker. Of course, it might run for years - literally - but what's a few eons to a computer?

BTW, you guys do realise that this question was from Jan. 2011, so I suspect Elvis has left the building.

Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 865
    
    5
One could of course devise a version with a probable solution still slower.

0) Grab a really good random generator.
...
step n)
pick randomly a "k" value between 0 and n.
pick randomly a string of the length "k"
compare it against the original one and if they are equal, the string of the length k,
otherwise repeat this very step.

No w I say if the random generator is really good, then with probability 1 you get the length with the above random algo.

Otherwise we had an infinite chain of wrong guesses.

First we see that the strings length will be picked almost surely (that is, with probability 1) in an infinite number of times.

Well, given for any R (>r) the probability that the right number "r" is not guessed any longer after step "R" is as follows.

At step R+1 we can pick R choices of R+1 to avoid the right choice, that is, R/(R+1)
At step R+2 we can pick R+1 choices of R+2 to avoid the right choice, that is, (R+1)/(R+2)
...

At step N it is (N-1) / N
That is, if the events are independent, then the cumulated probability is the product which telescopes to R/N.
With R being fixed and N tending to infinity, this tend to zero.
So with probability 1 we guessed the right length in an infinite times.

Now the probability of misguessing the given string from all the ones with this length is a fixed number near to 1 but below it.
And a given number (below 1) raised to the n-th power tends to zero.

Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4522
    
    5

From the subject line, the only restriction is on use of String#length(). So I would expect that it's allowed to use String#toCharArray().length

edit I see the OP mentions 'length properties' so I guess that rules that out.


luck, db
There are no new questions, but there may be new answers.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4240
    
    7

How about creating a JLabel with a monospace font and this text and then inferring the length from the preferred size of the JLabel? Is that indirect enough?
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 865
    
    5


But you of course cite the original assignment

without using any built in length methods or length properties.


and you could say BigInteger.bitLength is akind of built-in length method. and well, well, you were right then.


Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4522
    
    5

How about creating a JLabel ...
Interesting approach. TextLayout could give you a more accurate result.

hm, the OP stated
without using any built in length methods or length properties.
Seems to me that would exclude bitLength()
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String length without using String.length() method
 
Similar Threads
get the length of the string
How to find the length of a String without using the length method
Company Name is limited to 100 characters by DB, but text box allows more and thowing error
How to find a particular substring in a string without using any builtin methods of string
length of the string