文字列の均等分割
この問題は、除算だけでははく算術演算とか、文字列の長さをstrlenの類いで測るとかをしなくても、多分書けるのではないかと思います。
Posted feedbacks - C#
ごくごく普通ですが、 C#が無かったので。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System;
namespace bunkatsu
{
class Program
{
static void Main(string[] args)
{
string sample = "ゆめよりもはかなき世のなかをなげきわびつゝあかしくらすほどに四月十よひにもなりぬれば木のしたくらがりもてゆく";
divid(4, sample);
divid(5, sample);
divid(6, sample);
}
static public void divid(int n, string s)
{
int[] counts = new int[n];
for (int i = 0, j = 0; i < s.Length; ++i, ++j)
{
if (j >= n)
j = 0;
counts[j]++;
}
int start = 0;
for (int i = 0; i < n ; ++i)
{
Console.WriteLine( s.Substring( start, counts[i] ) );
start += counts[i];
}
}
}
}
|
残念。C# 先越されてしまいました。正規表現で文字数の算出と文字列の分割をやってます。
そういえば C# で text * n みたいなことやるメソッドって無いのかな。PadLeft と Replace で代用したけど。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System;
using System.Text.RegularExpressions;
static class Program {
static void Main() {
string text = "ゆめよりもはかなき世のなかをなげきわびつゝあかしくらすほどに四月十よひにもなりぬれば木のしたくらがりもてゆく";
Divide(4, text);
Divide(5, text);
Divide(6, text);
}
static void Divide(int cnt, string text) {
if (0 < cnt) {
int strlen = Regex.Matches(text, ".{1," + cnt + "}").Count;
bool skip = true;
foreach(Group g in Regex.Match(text, "".PadLeft(cnt).Replace(" ", "(.{" + (strlen - 1) + "," + strlen + "})")).Groups) {
Console.WriteLine(skip ? "" : g.Value);
skip = false;
}
}
}
}
|





nobsun
#4090()
Rating-1/3=-0.33
1 reply [ reply ]