We use nchar to find out how many characters are in a string. We use substring to get a part of a string.
nchar and substring in R Programming
nchar(x)
substring(text, first, last = 1000000)nchar(x) returns the number of characters in x.
substring(text, first, last) extracts characters from position first to last in text.
nchar("hello") # Returns 5
nchar("") # Returns 0
substring("programming", 1, 4) # Returns "prog"
substring("data", 3) # Returns "ta"
This program counts the letters in the word "education" and extracts letters from position 2 to 5.
word <- "education" length_of_word <- nchar(word) part_of_word <- substring(word, 2, 5) cat("Word:", word, "\n") cat("Number of characters:", length_of_word, "\n") cat("Substring from 2 to 5:", part_of_word, "\n")
Time complexity: Both nchar and substring run quickly, usually in constant time relative to string length.
Space complexity: substring creates a new string, so it uses extra space proportional to the substring length.
Common mistake: Forgetting that string positions start at 1 in R, not 0.
Use nchar when you need string length; use substring when you want part of a string.
nchar tells you how many characters are in a string.
substring lets you take a piece out of a string by giving start and end positions.
Positions in strings start at 1 in R, so count carefully.