Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String length without using String.length() method

 
Monish Kaushal
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 6088
71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you want this?
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With "normal" Java you can't. But with reflection you can:



But then again, why would you want this?
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could write a loop to call charAt method until you get an out of bounds exception.
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 147
Android Eclipse IDE Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quite inventive indeed!
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jelle Klap wrote:I know, but I still think it's cheating


But it solves the problem ;)
 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using character Array. You can calculate the size.
 
Ivan Jozsef Balazs
Rancher
Posts: 981
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10492
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ivan Jozsef Balazs
Rancher
Posts: 981
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 981
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic