String Manipulation Functions
Part of the Fundamentals section of Coddy's R journey — lesson 66 of 78.
Now that you know how to split strings into characters, let's explore a few essential functions for working with strings in R. These functions help you measure, combine, and transform text data.
The nchar() function returns the number of characters in a string:
word <- "hello"
print(nchar(word))Output:
[1] 5To combine multiple strings into one, use paste(). By default, it separates elements with a space:
result <- paste("Hello", "World")
print(result)Output:
[1] "Hello World"Use paste0() when you want no separator between strings:
result <- paste0("Hello", "World")
print(result)Output:
[1] "HelloWorld"For case conversion, R provides toupper() and tolower():
print(toupper("hello"))
print(tolower("WORLD"))Output:
[1] "HELLO"
[1] "world"These functions become powerful when combined with the iteration techniques you've learned, allowing you to process and transform text character by character or as whole strings.
Challenge
EasyYou will receive two lines of input:
- A first name (e.g.,
john) - A last name (e.g.,
SMITH)
Perform the following operations:
- Convert the first name to uppercase using
toupper() - Convert the last name to lowercase using
tolower() - Combine them into a full name using
paste()(with a space between) - Calculate the total number of characters in the full name (including the space) using
nchar() - Create a username by combining the first name and last name with no separator using
paste0(), all in lowercase - Print the full name
- Print the character count
- Print the username
For example, if the inputs are:
alice
WONDERThe output should be:
[1] "ALICE wonder"
[1] 12
[1] "alicewonder"Explanation: The first name "alice" becomes "ALICE" (uppercase), the last name "WONDER" becomes "wonder" (lowercase). The full name "ALICE wonder" has 12 characters (including the space). The username combines both names in lowercase with no separator: "alicewonder".
Cheat sheet
The nchar() function returns the number of characters in a string:
word <- "hello"
print(nchar(word)) # Output: [1] 5The paste() function combines multiple strings with a space separator by default:
result <- paste("Hello", "World")
print(result) # Output: [1] "Hello World"The paste0() function combines strings with no separator:
result <- paste0("Hello", "World")
print(result) # Output: [1] "HelloWorld"The toupper() function converts strings to uppercase, and tolower() converts to lowercase:
print(toupper("hello")) # Output: [1] "HELLO"
print(tolower("WORLD")) # Output: [1] "world"Try it yourself
# Read input
con <- file("stdin", "r")
first_name <- suppressWarnings(readLines(con, n = 1))
last_name <- suppressWarnings(readLines(con, n = 1))
close(con)
# TODO: Write your code below
# 1. Convert first_name to uppercase using toupper()
# 2. Convert last_name to lowercase using tolower()
# 3. Combine them into full_name using paste()
# 4. Calculate character count using nchar()
# 5. Create username using paste0() (all lowercase)
# Output the results
print(full_name)
print(char_count)
print(username)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values12Iterating Over Sequences
Iterating Over Vector ElementsUsing seq_along()Iterating Characters (strsplitString Manipulation Functions