Add separator to string at every N characters?
Regex.Replace(myString, ".{8}", "$0,");
If you want an array of eight-character strings, then the following is probably easier:
Regex.Split(myString, "(?<=^(.{8})+)");
which will split the string only at points where a multiple of eight characters precede it.
Add separator to string at every N characters Android?
Hello try below regular expression,
String s = "1234567890";
s = s.replaceAll("(.{3})", "$1:");
System.out.println(s);
Update:
Updated the answer, if you don't want to insert ':' at the end,
String s = "123456789";
s = s.replaceAll("...(?!$)", "$0:");
System.out.println(s);
"..." is the length. Which you can change if you want to. So if you want 84:F3:EB:34:75:6B like this as the output of 84F3EB34756B then use,
s = s.replaceAll("..(?!$)", "$0:");
How to insert a space into a string, between every 4 characters?
Assuming that it's fine to work from right-to-left, this should do the trick:
displaynum_lbl.Text = System.Text.RegularExpressions.Regex.Replace(printClass.mynumber.ToString(), ".{4}", "$0 ");
You can find that and a good deal more information in other StackOverflow answers, example: Add separator to string at every N characters?
How add separator to string at every N characters in swift?
Swift 5.2 • Xcode 11.4 or later
extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < endIndex else { return nil }
let end = index(start, offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
defer { start = end }
return self[start..<end]
}
}
func every(n: Int) -> UnfoldSequence<Element,Index> {
sequence(state: startIndex) { index in
guard index < endIndex else { return nil }
defer { let _ = formIndex(&index, offsetBy: n, limitedBy: endIndex) }
return self[index]
}
}
var pairs: [SubSequence] { .init(unfoldSubSequences(limitedTo: 2)) }
}
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func insert<S: StringProtocol>(separator: S, every n: Int) {
for index in indices.every(n: n).dropFirst().reversed() {
insert(contentsOf: separator, at: index)
}
}
func inserting<S: StringProtocol>(separator: S, every n: Int) -> Self {
.init(unfoldSubSequences(limitedTo: n).joined(separator: separator))
}
}
Testing
let str = "112312451"
let final0 = str.unfoldSubSequences(limitedTo: 2).joined(separator: ":")
print(final0) // "11:23:12:45:1"
let final1 = str.pairs.joined(separator: ":")
print(final1) // "11:23:12:45:1"
let final2 = str.inserting(separator: ":", every: 2)
print(final2) // "11:23:12:45:1\n"
var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2) // "11:23:12:45:1\n"
var str3 = "112312451"
str3.insert(separator: ":", every: 3)
print(str3) // "112:312:451\n"
var str4 = "112312451"
str4.insert(separator: ":", every: 4)
print(str4) // "1123:1245:1\n"
How to insert a character every N characters in a string in C++
std::string tokenize(const std::string& s) {
if (!s.size()) {
return "";
}
std::stringstream ss;
ss << s[0];
for (int i = 1; i < s.size(); i++) {
ss << '|' << s[i];
}
return ss.str();
}
How to add substring as separator to paragraph after every N words
You convert the string to an array, and then use map to add the separator:
extension String {
func add(separator: String, afterNWords: Int) -> String {
return split(separator: " ").enumerated().map { (index, element) in
index % afterNWords == afterNWords-1 ? "\(element) \(separator)" : String(element)
}.joined(separator: " ")
}
}
//Usage:
let result = paragraph.add(separator: "$$$$", afterNWords: 3)
Putting char into a java string for each N characters
Something like:
public static String insertPeriodically(
String text, String insert, int period)
{
StringBuilder builder = new StringBuilder(
text.length() + insert.length() * (text.length()/period)+1);
int index = 0;
String prefix = "";
while (index < text.length())
{
// Don't put the insert in the very first iteration.
// This is easier than appending it *after* each substring
builder.append(prefix);
prefix = insert;
builder.append(text.substring(index,
Math.min(index + period, text.length())));
index += period;
}
return builder.toString();
}
How can I insert a character after every n characters in javascript?
function chunk(str, n) {
var ret = [];
var i;
var len;
for(i = 0, len = str.length; i < len; i += n) {
ret.push(str.substr(i, n))
}
return ret
};
chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
How do you split a string at every n-th character in Swift?
Implement this function
extension String {
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
call it this way,
let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)
Output will be like this,
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28
This will be generic solution if you want to add any character instead of space, it will work.
Related Topics
Spawn Multiple Threads for Work Then Wait Until All Finished
How to Get Web Page's Content and Save It into the String Variable
Extension Methods Syntax VS Query Syntax
Should I Abstract the Validation Framework from Domain Layer
When Is a C# Value/Object Copied and When Is Its Reference Copied
When Should One Use Dynamic Keyword in C# 4.0
Entity Framework 6 Code First Custom Functions
Await Operator Can Only Be Used Within an Async Method
.Net Core Di, Ways of Passing Parameters to Constructor
Best Way to Convert Callback-Based Async Method to Awaitable Task
How to Get User Type C# Syntax Highlighting Working Again in VS 2012 Rc
Compile and Run Dynamic Code, Without Generating Exe
How to Display the Displayattribute.Description Attribute Value