Program to check : Length of String without using Strlen() Function
Definition & Explanation
Calculating the length of a string without using the strlen()
function involves iterating through the characters of the string until a null character ('\0'
) is encountered, which marks the end of the string.
Program Logic
Explanation:
- Initialize a counter to 0 to store the length of the string.
- Iterate through each character of the string.
- Increment the counter for each character until a null character is encountered, indicating the end of the string.
- Return the final counter value, which represents the length of the string.
Logic:
- Initialize a counter variable
length
to 0. - Iterate through the characters of the string until a null character (
'\0'
) is encountered. - For each character encountered, increment the counter variable
length
. - Return the value of
length
as the length of the string.
C
Method 1 :
#include <stdio.h>
int stringLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
const char *str = "Hello, World!";
int length = stringLength(str);
printf("Length of string: %d\n", length);
return 0;
}
Output :
C++
Method 1 :
#include <iostream>
using namespace std;
int stringLength(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
const char *str = "Hello, World!";
int length = stringLength(str);
cout << "Length of string: " << length << endl;
return 0;
}
Output :
JAVA
Method 1 :
public class StringLength {
public static int stringLength(String str) {
int length = 0;
while (str.charAt(length) != '\0') {
length++;
}
return length;
}
public static void main(String[] args) {
String str = "Hello, World!";
int length = stringLength(str);
System.out.println("Length of string: " + length);
}
}
Output :
Python
Method 1 :
def string_length(str):
length = 0
while str[length:]:
length += 1
return length
str = "Hello, World!"
length = string_length(str)
print("Length of string:", length)
Output :
Length of string: 13