I have a file test.txt
:
Stringsplittingskills
I want to read this file and write to another file out.txt
with three characters in each line like
Str
ing
spl
itt
ing
ski
lls
What I did
my $string = "test.txt".IO.slurp;
my $start = 0;
my $elements = $string.chars;
# open file in writing mode
my $file_handle = "out.txt".IO.open: :w;
while $start < $elements {
my $line = $string.substr($start,3);
if $line.chars == 3 {
$file_handle.print("$line\n")
} elsif $line.chars < 3 {
$file_handle.print("$line")
}
$start = $start + 3;
}
# close file handle
$file_handle.close
This runs fine when the length of string is not multiple of 3. When the string length is multiple of 3, it inserts extra newline at the end of output file. How can I avoid inserting new line at the end when the string length is multiple of 3?
I tried another shorter approach,
my $string = "test.txt".IO.slurp;
my $file_handle = "out.txt".IO.open: :w;
for $string.comb(3) -> $line {
$file_handle.print("$line\n")
}
Still it suffers from same issue.
I looked for here, here but still unable to solve it.
Take originalString and split it an array of smaller chunks. Each chunk must be precisely equal in length to maxLength, with the possible exception of the last chunk. The last chunk consists of the remaining characters. Its length is less or equal to maxLength. => The subString () methods of String appear a bit clumsy to implement this logic.
Each chunk must be precisely equal in length to maxLength, with the possible exception of the last chunk. The last chunk consists of the remaining characters. Its length is less or equal to maxLength. => The subString () methods of String appear a bit clumsy to implement this logic.
1 Using LINQ We can use LINQ’s Select () method to split a string into substrings of equal size. ... 2 Using String.Substring () method Another solution is to simply use the String.Substring () method to break the string into substrings of the given size, as shown below: 1 2 ... 3 Using Regex
Using LINQ We can use LINQ’s Select () method to split a string into substrings of equal size. The following code example shows how to implement this: 2.
spurt "out.txt", "test.txt".IO.comb(3).join("\n")
Another approach using substr-rw
.
subset PositiveInt of Int where * > 0;
sub break( Str $str is copy, PositiveInt $length )
{
my $i = $length;
while $i < $str.chars
{
$str.substr-rw( $i, 0 ) = "\n";
$i += $length + 1;
}
$str;
}
say break("12345678", 3);
Output
123
456
78
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With