Count Number of Characters in String in R

• Last Updated : 16 May, 2021

In this article, we will discuss how to find the number of characters in a string using R Programming Language. The number of characters in a string means the length of the string.

Examples:

Input: Geeksforgeeks

Output: 13

Explanation: Total 13 characters in the given string.

Input: Hello world

Output: 11

This can be calculated using the below-mentioned functions:

• Using nchar() method
• Using str_length() method
• Using stri_length() method

Method 1: Using nchar() method.

nchar() method in R programming is used to get the length of a string.

Syntax: nchar(string)

Parameter: string

Return: Returns the length of a string

Code:

R

 # R program to calculate length # of string  # Given Stringgfg <- "Geeks For Geeks"  # Using nchar() methodanswer <- nchar(gfg)  print(answer)

Output:

 15

This method can be used to return the length of multiple strings passed as a parameter.

Code:

R

 nchar(c("Hello World!","Akshit"));

Output:

 12  6

Method 2. Using str_length () method.

The function str_length() belonging to the ‘stringr’ package can be used to determine the length of strings in R.

Syntax: str_length (str)

Parameter: string as str

Return value: Length of string

Code:

R

 # R program for finding length# of string  # Importing packagelibrary(stringr)  # Calculating length of string    str_length("hello")

Output:

 5

This method can be used to return the length of multiple strings passed as a parameter.

Code:

R

 # Codelibrary(stringr);  str_length(c("Hello World!","Akshit"));

Output:

 12  6

Method 3. Using stri_length() method.

This function returns the number of code points in each string.

Syntax: stri_length(str)

Parameter: str as character vector

Return Value: Returns an integer vector of the same length as str.

Note that the number of code points is not the same as the `width` of the string when printed on the console.

Code:

R

 library(stringi);  stri_length(c("Akshit"));

Output:

 6

This method can be used to return the length of multiple strings passed as a parameter.

R

 library(stringi);  stri_length(c("Hello World","Akshit"));

Output:

 11  6

My Personal Notes arrow_drop_up