java 字符串如何在java中终止?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3974398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how string terminates in java?
提问by daydreamer
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
嗨,
我正在尝试编写一个递归函数来计算 Java 中字符串的长度
我知道已经存在 str.length() 函数,但是问题陈述想要实现一个递归函数
In C programming language the termination character is '\0', I just want to know how to know if string ends in Java
在C编程语言中,终止符是'\0',我只想知道如何知道字符串是否以Java结尾
My program ends well when I put '\n' in the test string. Please let me know. Thanks!
当我将 '\n' 放入测试字符串时,我的程序结束得很好。请告诉我。谢谢!
/*
* 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);
}
}
Output :
输出 :
run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)
采纳答案by Upul Bandara
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));
}
回答by Ignacio Vazquez-Abrams
Java strings are not C strings. The string ends after the number of characters in its length.
Java 字符串不是 C 字符串。字符串在其长度的字符数之后结束。