-6

My roommate's teacher gave them a assignment to implement string length method in JAVA? we have thought out two ways.

  1. Check the element,and when get the out of bounds exception,it means the end of string,we catch this exception,then we can get the length.

  2. Every time a string is pass to calculate the length,we add the special character to the end of it,it can be '\0',or "A",etc..

But we all think this two way may can finish the assignment,but they are bad(or bad habit to do with exception),it's not cool.

And we have googled it,but don't get what we want.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Wythe
  • 149
  • 3
  • 12
  • 1
    The assignment does not make any sense. Regardless of how you “implement” it, including your two attempts and all the answers given so far, it always implicitly relies on the fact that the `String` already knows its length. So the solution regardless of how it looks like always uses the already known length to do something fancy concealing that it finally reconstructs the length that was already given in the first place. – Holger Aug 05 '14 at 16:16

5 Answers5

1

The pseudo-code you probably want is:

counter = 0
for(Character c in string) {
    counter = counter + 1
}

This requires you to find a way to turn a Java String into an array of characters.

Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
1

Something like this?

int i = 0;
for (char ch : string.toCharArray()) {
  i++;
}
chaseoes
  • 89
  • 5
  • but how do you be sure if is the end? – Wythe Aug 05 '14 at 23:58
  • Because the `foreach` loop is defined to traverse each element in the array exactly once. This is a reasonable solution to the problem of computing a String's length without using the String.length() method (though there is a simpler approach). It does have the drawback of requiring additional O(n) memory. For small strings, that wouldn't be a problem. For really large strings, it could be. – Andy Thomas Aug 06 '14 at 00:54
  • OK.i.m curious about the simpler approach – Wythe Aug 06 '14 at 02:48
  • @myqiqiang - See the edit in my answer. After you've got the char[], there's no need to iterate through it to get the length. – Andy Thomas Aug 06 '14 at 03:24
1

Likely the teacher is trying to make his or her students think, and will be satisfied with creative solutions that solve the problem.

None of these solutions would be used in the real world, because we have the String.length() method. But the creative, problem-solving process you're learning would be used in real development.

"1. Check the element,and when get the out of bounds exception,it means the end of string,we catch this exception,then we can get the length."

Here, you're causing an exception to be thrown in the normal case. A common style guideline is for exceptions to be thrown only in exceptional cases. Compared to normal flow of control, throwing an exception can be more expensive and more difficult to follow by humans.

That said, this one of your ideas has a potential advantage for very long strings. All of the posted answers so far run in linear time and space. The time and/or additional space they take to execute is proportional to the length of the string. With this approach, you could implement an O(log n) search for the length of the string.

Linear or not, it's possible that the teacher would find this approach acceptable for its creativity. Avoid if the teacher has communicated the idea that exceptions are only for exceptional cases.

"2. Every time a string is pass to calculate the length,we add the special character to the end of it,it can be '\0',or "A",etc.."

This idea has a flaw. What happens if the string contains your special character?

EDIT

A simple implementation would be to get a copy of the underlying char array with String.toCharArray(), then simply take its length. Unlike your ideas, this is not an in-place approach - making the copy requires additional space in memory.

    String s = "foo";
    int length = s.toCharArray().length;
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Why do you think that the first approach has `O(log(n))`? As it stands there “*when get the out of bounds exception,it means the end of string*” it implies a *linear search*. – Holger Aug 05 '14 at 16:24
  • @Holger - I think the OP is probably implicitly referring to a linear traversal of the string. But the OP *explicitly* refers to the general idea of checking elements of the string, and this could be done in a non-linear, O(log n) manner. – Andy Thomas Aug 05 '14 at 16:28
  • you seem to be talking about a binary search but since you don’t know the length, you would need to scan the entire 2³¹ search space. Great, that means that the algorithm is even `O(1)` as it does not depend on the `String`’s length but generating and catching up to 31 exceptions also means that the normal exception-free linear search will likely be faster even for the longest `String`s. A good example for the limitations of the `O(…)` notation. – Holger Aug 05 '14 at 16:40
  • @Holger - You're right that the constant factors would be significantly higher per-element with the exception-throwing approach. But I suspect you're overestimating the cost of 31 exceptions versus 2^31 checked accessor calls. Testing now ... – Andy Thomas Aug 05 '14 at 16:55
  • It may heavily depend on the JVM version and, of course, how deep the actual stack to be traced is. In the past, exceptions were really slow due to the fact they ought to be, well, exceptional, e.g. the JVMs made not even an attempt to hand over exception handlers to the JIT. In contrast, linear search code is perfectly optimizable for a JVM. – Holger Aug 05 '14 at 17:11
  • @Holger - Actual measurements with a modern VM: 2^31 checked accesses = 1,672 ms. 31 exceptions = 0 ms. (10,000 exceptions measured at 15 ms.) Exceptions are more expensive than normal flow of control, but they're not the same as waiting for Christmas. :) This is an academic exercise that one would not use in the real world with the extant String API. If it were an actual performance hack with some other strangely lacking API, one would want to switch over to linear search once the search space decreased below a threshold. – Andy Thomas Aug 05 '14 at 17:25
  • all you said.maybe both mine and above answers are not good.So.how will you implement this method.i also wonder how java or Sun implement this method.IT seems that we cannot disscuss out a good solution – Wythe Aug 05 '14 at 23:57
  • @myqiqiang - The String class itself has access to its char[] representation, and can simply (in modern implementations) return the length of that array. If you are developing your own String class, you could do the same thing. If you're writing a utility method that can't call String.length(), the solutions include: A) Your idea of calling charAt() until it fails, B) call `String.toCharArray().length()`, C) new StringBuilder( mystring).length(). A does not require additional memory, but uses an exception in normal flow of control. See comments on B above. – Andy Thomas Aug 06 '14 at 01:04
0

Try this

public static int Length(String str) {
    str = str + '\0';
    int count = 0;

    for (int i = 0; str.charAt(i) != '\0'; i++) {
        count++;
    }

    return count;
}
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
kirti
  • 4,499
  • 4
  • 31
  • 60
-1

What about:

"your string".toCharArray().length
Vincent Durmont
  • 813
  • 8
  • 16