In a given string vector i am trying to add a break line("\n") at every character with some conditions(described below). the below string which i am passing
d <- "ABCD CDEFG LM NOPQRSTR";
output expected:
"ABCD\n //added new break line \n at fourth character which contained space
CDEF\n //after the fourth character is C, added a new break line \n
-G LM\n //started with hypen(-) continuing with the characters.
NOPQ\n
-RSTR"
Condition:
add a new break line i,e "\n" for every 4 characters position if and only based on the below logic
if the character=""(blank) then
add break to next line ("\n") at 4th character like above sample output(ABCD\n) reset
character continues
else then if character <> "" like (character including number or special character) then
add break to next line("\n") at 4th character(CDEF\n) along with hypen(-) i,e C in
next line
Hope I made my best to explain the problem. free to write if it is still not understood. Code I tried: I am new to the R world , this is the logic i tried. Please Help
c <- 4 //setting the position index
for (i in 1:nchar(d)){
//print(substr(d, i,i))
a<-substr(d, i,c) //get the 4th index
if(a=""){ //if 4th character is blank
d<-paste0(a,"\n") //add a break new line (\n)
}else {
d<-paste0("-",a) //if the character contains 4th is a character put that character in
next line continue with -
}
}
I am unable return complete string with the breakline adding(\n for every 4th character) and -(if it contains as shown in the sample expected output)
I got the inspirations with the below link , but not able to crack up.
Thanks in advance