How to find the numbers of characters in a string in R

Overview

A string like in every other programming language is used to store text. A string is always written in single quotation marks ('') or double quotation marks(""). Examples are: 'Hello world', "Hello World", etc.

These texts can also be referred to as characters. For instance, the first character in the string "Hello world" is "H", the sixth character is a space " " and the last character of the string is d.

To check for the number of characters present in a string, we use the nchar() function of R.

Syntax

nchar(string)

Parameter(s)

  • string: Where the parameter value is the string variable in which you wish to find the number of characters present in it.

Example code

let’s create a string and calculate the number of characters present in that string.

# creating a string
mystring <- "Hello World!"
# using the nchar() function
nchar(mystring)

From the output of the code above, we can see that using the nchar() function, the string "Hello World" contains just 12 characters.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources