YouTip LogoYouTip

R Func Nchar

# R nchar() Function - Get Character Count [![Image 3: R Language Examples](#) R Language Examples](#) R nchar() function is used to count the number of characters in a string. nchar() can handle multi-byte characters such as Chinese, and is one of the most fundamental functions in string processing. The syntax of nchar() function is as follows: nchar(x, type = "chars") **Parameter Description:** * **x** Input string vector. * **type** Counting type: "chars" (character count), "bytes" (byte count), "width" (display width). ## Example # English and Chinese text_en <-"Hello TUTORIAL" text_cn <-"HelloWorld" print(paste("English:", nchar(text_en))) print(paste("Chinese:", nchar(text_cn))) # Character count in vector words <-c("R", "Python", "JavaScript", "Go") print("Character count per language:") print(nchar(words)) # Check the difference between byte count and character count text<-"Hello World" print(paste("Character count:", nchar(text, type ="chars"))) print(paste("Byte count:", nchar(text, type ="bytes"))) Executing the above code outputs: "English: 12" "Chinese: 4" "Character count per language:" 1 6 10 2 "Character count: 8" "Byte count: 13" nchar() combined with substr() can implement string truncation: ## Example # Truncate overly long strings and add ellipsis texts <-c("This is a long description text that needs to be truncated", "Short text") truncate max_len, paste0(substr(x, 1, max_len), "..."), x) } print("Truncation result:") print(truncate(texts, max_len =8)) Executing the above code outputs: "Truncation result:" "This is a very long desc..." "Short text" [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func ParR Func Min Max β†’