← Back to R Course | Chapter 6: Strings | Lesson 6 of 7

strsplit

strsplit chops a piece of text into parts wherever a separator appears, like cutting a sandwich at each line. A sentence can become a list of words this way.

In this page:

  1. strsplit
Syntax
r
parts <- strsplit(x, split)
parts[[1]]

strsplit

strsplit(x, split) splits a string into pieces wherever the separator pattern occurs, returning a list (since each input string could split into a different number of pieces).

Accessing the first result requires indexing into the list, like strsplit(x, ",")[[1]]. This is the standard way to parse delimited text like CSV rows.

Note: strsplit() always returns a list, even for a single string input -- use [[1]] to get the character vector of pieces out.

Example: strsplit

markup
csv_line <- "apple,banana,cherry"

parts <- strsplit(csv_line, ",")[[1]]
print(parts)
cat("Second item:", parts[2], "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Treating the result as a vector and writing parts[2] directly, when strsplit returns a list and you need [[1]] first.
  2. Splitting on a special regex character like "." or "|", which matches unexpectedly; use fixed = TRUE.
  3. Expecting an empty piece at the end of a string ending in the separator, when a trailing empty string is dropped.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.