Find the Length of a String
Solve this ProblemEasy5 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return how many characters it contains. Spaces and punctuation count.
A stringStringA sequence of characters, such as letters, digits, spaces and punctuation, treated as one value. is a sequence of characters, and its length is how many there are. Most languages store that number with the string, but C marks the end with a hidden null terminatorNull TerminatorThe character \0 that C places after the last character of a string to mark where it ends. instead, so counting characters is a real loop there.
Test Case 1:
Input:text = "hello"
Output:5
Explanation:Five characters.
Test Case 2:
Input:text = "a b"
Output:3
Explanation:The space is a character too.
Constraints
- ◆
1 ≤ text.length ≤ 1000 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Count Characters One by OneGood
Walk through the string and add one to a counter for every character, spaces included. In C a string has no stored length: it ends at the invisible '\0' character, so the loop runs until it reaches that terminator.
Time
O(n)Space
O(1)Java
class Solution {
public int lengthOf(String text) {
int count = 0;
for (char ch : text.toCharArray()) {
count++;
}
return count;
}
}Built-in LengthOptimal
Use the language's length: text.length() in Java, len(text) in Python, text.size() in C++, strlen(text) in C and text.length in JavaScript. Java, Python, C++ and JavaScript store the length with the string, so this is instant; C's strlen still has to walk to the terminator.
Time
O(1) (O(n) in C)Space
O(1)Java
class Solution {
public int lengthOf(String text) {
return text.length();
}
}