[英]Implement String.length method by hand
I have to implement the.length method from String
class "by hand" and I have no idea and hope you can help somehow.我必须“手动”实现
String
class 中的 .length 方法,我不知道,希望你能以某种方式提供帮助。 No other methods or functions are allowed, than:除了:
static void manual_length2(String length) {
//example String length = "Hello" = 5 letters.
int counter = 0;
int i = 0;
char g = ' ';
while(i <= 4 ) { /*4 is the number i already know */
g = length.charAt(i);
counter += 1;
length.substring(1);
++i;
}
System.out.println(counter); System.out.println(计数器);
Console: 5控制台:5
This was my approach, but I'm stuck in the while statement's condition to terminate.这是我的方法,但我被困在 while 语句的终止条件中。 With the example "Hello" i already know that this word has 5 letters, but it needs to fit for all inputs.
通过示例“Hello”,我已经知道这个词有 5 个字母,但它需要适合所有输入。 So i don't know how to express to border-value of the while statement.
所以我不知道如何表达 while 语句的边界值。
Another approach is by recursion, but also, i ask myself how can i express the limit of the recursion.另一种方法是递归,但我问自己如何表达递归的限制。 How can i express:
我该如何表达:
.... lengthMethod1(String length, int ???) {
if(n == 0) {
return length.charAt(0);
}
else {
return ???? lengthMethod1(length, n - 1);
} }
You can loop until the String
is empty while removing the first character on each iteration.您可以循环直到
String
为空,同时在每次迭代中删除第一个字符。
static int manual_length(String str) {
int len = 0;
while(!str.isEmpty()){
++len;
str = str.substring(1);
}
return len;
}
This can be converted to a tail-recursive method as well.这也可以转换为尾递归方法。
static int manual_length(String str) {
return str.isEmpty() ? 0 : 1 + manual_length(str.substring(1));
}
Another approach is by recursion, but also, i ask myself how can i express the limit of the recursion.
另一种方法是递归,但我问自己如何表达递归的限制。 How can i express:
我该如何表达:
Yes, you can do recursively like this:是的,你可以像这样递归地做:
static int manual_length(String str, int len) {
return str.isEmpty() ? len : manual_length(str.substring(1), len + 1);
}
You use an accumulator variable ( ie, len ), that you increment, while removing a char from the string ( ie, str.substring(1)
).您使用一个累加器变量(即len )来增加,同时从字符串中删除一个字符(即
str.substring(1)
)。 When you reach the end ( ie, str.isEmpty()
) you return the accumulator.当您到达终点(即
str.isEmpty()
)时,您将返回累加器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.