Iterating Characters (strsplit
Part of the Fundamentals section of Coddy's R journey — lesson 65 of 78.
What if you need to process each character in a string individually? Unlike vectors, you can't directly loop through a string's characters in R. The strsplit() function solves this by splitting a string into a vector of characters.
The strsplit() function takes two arguments: the string to split and the separator. To split into individual characters, use an empty string "" as the separator:
word <- "hello"
chars <- strsplit(word, "")[[1]]
print(chars)Output:
[1] "h" "e" "l" "l" "o"Notice the [[1]] at the end. This is because strsplit() returns a list, and we need to extract the first element to get our character vector. Once you have the characters as a vector, you can iterate over them using the techniques you've already learned:
word <- "R"
chars <- strsplit(word, "")[[1]]
for (char in chars) {
print(char)
}Output:
[1] "R"This technique is essential for tasks like counting specific characters, reversing strings, or validating input character by character.
Challenge
EasyYou will receive a single line of input containing a word (e.g., programming).
Using strsplit() to split the string into individual characters:
- Split the input word into a vector of characters
- Loop through each character in the vector
- Count how many times the letter
"a"appears in the word (case-sensitive) - Print each character on its own line using
print() - After the loop, print the count using
cat()with the format:Count of 'a': Xfollowed by a newline
For example, if the input is:
bananaThe output should be:
[1] "b"
[1] "a"
[1] "n"
[1] "a"
[1] "n"
[1] "a"
Count of 'a': 3Explanation: The word "banana" is split into characters c("b", "a", "n", "a", "n", "a"). Each character is printed, and the letter "a" appears 3 times.
Cheat sheet
To split a string into individual characters, use strsplit() with an empty string "" as the separator:
word <- "hello"
chars <- strsplit(word, "")[[1]]
print(chars)Output:
[1] "h" "e" "l" "l" "o"The [[1]] extracts the first element from the list returned by strsplit(), giving you a character vector.
You can then loop through the characters:
word <- "R"
chars <- strsplit(word, "")[[1]]
for (char in chars) {
print(char)
}Try it yourself
# Read input
con <- file("stdin", "r")
word <- suppressWarnings(readLines(con, n = 1))
# Initialize counter for letter 'a'
count_a <- 0
# TODO: Write your code below
# 1. Use strsplit() to split the word into individual characters
# 2. Loop through each character
# 3. Print each character using print()
# 4. Count how many times 'a' appears
# Output the count of 'a'
cat("Count of 'a': ", count_a, "\n", sep = "")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