R Program to Print a New Line in String
In this article, we will discuss how to print a new line in a string using R Programming Language.
Method 1: Using cat() function
In this method, the need to call the cat() function which is here responsible to print text and text.
Syntax: cat(text/file = “”, sep = ” “, fill = FALSE, labels = NULL, append = FALSE)
Parameters:
- Text/file: text or file you want to print.
- sep: separator
- fill: If fill=TRUE, a new line will be printed if page is filled.
- labels: labels if any
R
# storing strings in variables string1 <- "Beginner" string2 <- "FOR" string3 <- "Beginner" # passing variable in cat() without new # line serperator cat (string1,string2,string3) # passing a string using \n to split cat ( "Beginner \nFOR \nBeginner" ) # passing variables using \n cat (string1, "\n" ,string2, "\n" ,string3) |
Output:
Beginner FOR Beginner
Beginner
FOR
Beginner
Beginner
FOR
Beginner
Method 2: Using writeLines() function
In this method, the user has to use the writeline() function by calling it and passing it with the required parameters in the R programming language.
writeLines() is used to write lines in a connection.
Syntax: writeLines(text, con = stdout(), sep = “\n”, useBytes = FALSE)
Parameters:
- Text: text you want to print
- con: A connection object or a character string.
- Sep: separator
- UseBytes: True/False
R
# declaring variable x <- "Beginner \n FOR \n Beginner" # print x variable writeLines (x) # printing a string with \n new line writeLines ( "Beginner \nFOR \nBeginner" ) |
Output:
Beginner
FOR
Beginner
Beginner
FOR
Beginner
Approach: Split and Print New Line
- The printNewLine() function takes a string as an input argument.
- The strsplit() function is used to split the string into individual characters, which are stored in a vector.
- The for loop iterates over each character in the vector, printing it using the cat() function.
- If the character is a space, the cat() function is used to print a newline character (\n) to create a new line in the output.
R
printNewLine <- function (string) { splitString <- strsplit (string, split = "" )[[1]] for (i in 1: length (splitString)) { cat (splitString[i]) if (splitString[i] == " " ) { cat ( "\n" ) } } } # Example usage: printNewLine ( "Beginner FOR Beginner" ) |
OUTPUT
Beginner FOR Beginner
Contact Us