我有一个字符串变量,其值为 “abcdefghijklmnop”。
拆分没有分隔符的字符串
现在我要拆分的字符串转换成字符串数组与说3个字符(最后一个数组元素可以包含以下)从右侧端的每个数组元素。
即,
“一”
“BCD”
“EFG”
“HIJ”
“荷航”
“NOP”
什么是最简单,最简单的如何做到这一点? (欢迎使用vb和C#代码)
我有一个字符串变量,其值为 “abcdefghijklmnop”。
拆分没有分隔符的字符串
现在我要拆分的字符串转换成字符串数组与说3个字符(最后一个数组元素可以包含以下)从右侧端的每个数组元素。
即,
“一”
“BCD”
“EFG”
“HIJ”
“荷航”
“NOP”
什么是最简单,最简单的如何做到这一点? (欢迎使用vb和C#代码)
这里的一个解决方案:
var input = "abcdefghijklmnop";
var result = new List<string>();
int incompleteGroupLength = input.Length % 3;
if (incompleteGroupLength > 0)
result.Add(input.Substring(0, incompleteGroupLength));
for (int i = incompleteGroupLength; i < input.Length; i+=3)
{
result.Add(input.Substring(i,3));
}
给出的预期输出:
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
正则表达式时间!
Regex rx = new Regex("^(.{1,2})??(.{3})*$");
var matches = rx.Matches("abcdefgh");
var pieces = matches[0].Groups[1].Captures.OfType<Capture>().Select(p => p.Value).Concat(matches[0].Groups[2].Captures.OfType<Capture>().Select(p => p.Value)).ToArray();
片将包含:
"ab"
"cde"
"fgh"
(请不要使用此代码只有当你使用正则表达式+ LINQ的什么都有可能发生的例子!)
下面是一些工作 - 包装成一个字符串扩展功能。
namespace System
{
public static class StringExts
{
public static IEnumerable<string> ReverseCut(this string txt, int cutSize)
{
int first = txt.Length % cutSize;
int taken = 0;
string nextResult = new String(txt.Take(first).ToArray());
taken += first;
do
{
if (nextResult.Length > 0)
yield return nextResult;
nextResult = new String(txt.Skip(taken).Take(cutSize).ToArray());
taken += cutSize;
} while (nextResult.Length == cutSize);
}
}
}
用法:
textBox2.Text = "";
var txt = textBox1.Text;
foreach (string s in txt.ReverseCut(3))
textBox2.Text += s + "\r\n";
well..here是另一种方式,我来到..
private string[] splitIntoAry(string str)
{
string[] temp = new string[(int)Math.Ceiling((double)str.Length/3)];
while (str != string.Empty)
{
temp[(int)Math.Ceiling((double)str.Length/3) - 1] = str.Substring(str.Length - Math.Min(str.Length, 3));
str = str.Substring(0, str.Length - Math.Min(str.Length, 3));
}
return temp;
}
对不起,我显然不能今天看了。 –