0
0
R Programmingprogramming~5 mins

nchar and substring in R Programming

Choose your learning style9 modes available
Introduction

We use nchar to find out how many characters are in a string. We use substring to get a part of a string.

When you want to count the letters in a word or sentence.
When you need to cut out a piece of a text, like a name or code.
When checking if a string is too long or too short.
When extracting a specific part from a string, like area code from a phone number.
When cleaning or formatting text data by taking only needed parts.
Syntax
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.

Examples
Counts the letters in the word "hello".
R Programming
nchar("hello")
# Returns 5
Empty string has zero characters.
R Programming
nchar("")
# Returns 0
Gets the first 4 letters from "programming".
R Programming
substring("programming", 1, 4)
# Returns "prog"
Gets substring from position 3 to the end.
R Programming
substring("data", 3)
# Returns "ta"
Sample Program

This program counts the letters in the word "education" and extracts letters from position 2 to 5.

R Programming
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")
OutputSuccess
Important Notes

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.

Summary

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.