Menu
Coddy logo textTech

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 icon

Challenge

Easy

You will receive a single line of input containing a word (e.g., programming).

Using strsplit() to split the string into individual characters:

  1. Split the input word into a vector of characters
  2. Loop through each character in the vector
  3. Count how many times the letter "a" appears in the word (case-sensitive)
  4. Print each character on its own line using print()
  5. After the loop, print the count using cat() with the format: Count of 'a': X followed by a newline

For example, if the input is:

banana

The output should be:

[1] "b"
[1] "a"
[1] "n"
[1] "a"
[1] "n"
[1] "a"
Count of 'a': 3

Explanation: 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 = "")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals