Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string every 5 characters

Suppose I have a long string:

"XOVEWVJIEWNIGOIWENVOIWEWVWEW" 

How do I split this to get every 5 characters followed by a space?

"XOVEW VJIEW NIGOI WENVO IWEWV WEW" 

Note that the last one is shorter.

I can do a loop where I constantly count and build a new string character by character but surely there must be something better no?

like image 389
user1357015 Avatar asked Oct 21 '14 22:10

user1357015


People also ask

How do you split a string at every nth character?

To split a string every nth character:Use a list comprehension to iterate over a range with step N. On each iteration, use string slicing to select a slice of the string. The list will contain string slices with maximum length of N.

Can a string be split on multiple characters?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.

How do you split a string after a specific number of characters in Python?

Use range() function and slicing notation to split string by a number of characters in Python.


1 Answers

Using regular expressions:

gsub("(.{5})", "\\1 ", "XOVEWVJIEWNIGOIWENVOIWEWVWEW") # [1] "XOVEW VJIEW NIGOI WENVO IWEWV WEW" 
like image 89
flodel Avatar answered Oct 01 '22 20:10

flodel