字符串如何在java中终止? [英] how string terminates in java?
问题描述
嗨
我正在尝试编写一个递归函数来计算Java中字符串的长度
我知道已经存在str.length()函数,但是问题语句想要实现一个递归函数
Hi
I am trying to write a recursive function which calculates the length of string in Java
I know that there already exists str.length() function, but the problem statement wants to implement a recursive function
在C编程语言中,终止字符是'\ 0',我只想知道如何知道字符串是否以Java结尾
In C programming language the termination character is '\0', I just want to know how to know if string ends in Java
当我在测试字符串中放入'\ n'时,我的程序结束得很好。请告诉我。谢谢!
My program ends well when I put '\n' in the test string. Please let me know. Thanks!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package careercup.google;
/**
*
* @author learner
*/
public class Strlen {
private static final String Test = "abcdefg\n";
private static int i =0;
public static void main(String args[]){
System.out.println("len : " + strlen(Test));
}
private static int strlen(String str){
if(str == null){
return 0;
}
if(str.charAt(i) == '\n'){
return 0;
}
i += 1;
return 1 + strlen(str);
}
}
输出:
run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)
推荐答案
请记住,此代码效率非常低,但它在递归时计算字符串的
长度方式。
Please keep in mind that this code is very inefficient, but it calculates length of a String in recursive way.
private static int stringLength(String string){
if(string == null){
return 0;
}
if(string.isEmpty()){
return 0;
}
return 1 + stringLength(string.substring(1));
}
这篇关于字符串如何在java中终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!