String Length Implementation Java
Chapter:
String Handling
Last Updated:
02-12-2019 11:05:29 UTC
Program:
/* ............... START ............... */
public class JavaStringLength {
public static void main(String args[]) {
System.out.println("String length Implementation");
String str ="string implementation";
System.out.println("String Length : " + stringLenth(str));
}
public static int stringLenth(String str) {
if (str == null)
return 0;
char[] stringToCharArray = str.toCharArray();
int i = 0, length = 0;
while (i < stringToCharArray.length) {
i++;
length++;
}
return length;
}
}
/* ............... END ............... */
Output
String length Implementation
String Length : 21
Notes:
-
For string length implementation we have used char array to store the string as an array of character and by using while loop iterate for all character in the char array.
- In each iteration length field will be incremented by one.
- If string is null it will return value as zero at the initial step.
- Java built in function to find the length of the string is length(). eg : str.length()
Tags
String implementation java, String Length Implementation