如何使用C#将字符串拆分为一个由两个字母组成的子字符串数组



问题

给定一个示例字符串abcdef,我试图将其拆分为一个由两个字符串元素组成的数组,该数组应产生['ab','cd','ef']

我尝试了什么

在将子字符串存储在方法内部声明的数组中的当前索引中时,我尝试迭代该字符串,但得到了以下输出['ab','bc','cd','de','ef']

我使用的代码

static string[] mymethod(string str)
{
string[] r= new string[str.Length];
for(int i=0; i<str.Length-1; i++)
{
r[i]=str.Substring(i,2);
}
return r;
}

任何纠正这一问题的解决方案,用代码返回正确的输出,都是非常受欢迎的,谢谢

您的问题是每次都将索引增加1而不是2

var res = new List<string>();
for (int i = 0; i < x.Length - 1; i += 2)
{
res.Add(x.Substring(i, 2));
}

应该工作

编辑:因为在奇数字符数量的情况下要求默认的CCD_ 4后缀,这应该是改变:

var testString = "odd";
string workOn = testString.Length % 2 != 0
? testString + "_"
: testString;
var res = new List<string>();
for (int i = 0; i < workOn.Length - 1; i += 2)
{
res.Add(workOn.Substring(i, 2));
}

两个注意事项:

  • 英寸。NET 6Chunk()可用,因此您可以按照其他答案中的建议使用它
  • 在输入很长的情况下,这种解决方案可能不是最好的所以这实际上取决于你的投入和期望

.net 6有一个IEnumerable.Chunk()方法,您可以使用它来执行此操作,如下所示:

public static void Main()
{
string[] result = 
"abcdef"
.Chunk(2)
.Select(chunk => new string(chunk)).ToArray();
Console.WriteLine(string.Join(", ", result)); // Prints "ab, cd, ef"
}

在.net 6之前,您可以使用MoreLinq.Batch()来做同样的事情。


[EDIT]响应以下请求:

MoreLinq是一组Linq实用程序,最初由Jon Skeet编写。您可以通过转到Project | Manage NuGet Packages,然后浏览MoreLinq并安装它来找到实现

安装后,添加using MoreLinq.Extensions;,然后您就可以使用MoreLinq.Batch扩展,如下所示:

public static void Main()
{
string[] result = "abcdef"
.Batch(2)
.Select(chunk => new string(chunk.ToArray())).ToArray();
Console.WriteLine(string.Join(", ", result)); // Prints "ab, cd, ef"
}

请注意,没有接受IEnumerable<char>的字符串构造函数,因此需要上面的chunk.ToArray()

不过,我想说,仅仅为了一个扩展方法而包括整个MoreLinq可能有些过头了。您可以为Enumerable.Chunk()编写自己的扩展方法:

public static class MyBatch
{
public static IEnumerable<T[]> Chunk<T>(this IEnumerable<T> self, int size)
{
T[] bucket = null;
int count  = 0;
foreach (var item in self)
{
if (bucket == null)
bucket = new T[size];
bucket[count++] = item;
if (count != size)
continue;
yield return bucket;
bucket = null;
count  = 0;
}
if (bucket != null && count > 0)
yield return bucket.Take(count).ToArray();
}
}

如果您使用的是最新的。NET版本,即(.NET 6.0 RC 1),然后您可以尝试Chunk()方法,

var strChunks = "abcdef".Chunk(2); //[['a', 'b'], ['c', 'd'], ['e', 'f']]
var result = strChunks.Select(x => string.Join('', x)).ToArray(); //["ab", "cd", "ef"]

注意:由于的最新版本,我无法在fiddle或本地机器上测试此功能。净

使用linq可以通过以下方式实现:

char[] word = "abcdefg".ToCharArray();
var evenCharacters = word.Where((_, idx) => idx % 2 == 0);
var oddCharacters = word.Where((_, idx) => idx % 2 == 1);
var twoCharacterLongSplits = evenCharacters
.Zip(oddCharacters)
.Select((pair) => new char[] { pair.First, pair.Second });

诀窍如下,我们创建两个集合:

  • 其中我们只有那些原始索引为甚至的字符(% 2 == 0)
  • 其中我们只有那些原始索引为奇数的字符(% 2 == 1)

然后我们把它们拉上拉链。因此,我们通过从偶数集合中提取一个项,从奇数集合中获取一个项来创建元组。然后,我们通过从偶数和…中提取一个项来创建一个新的元组。。。

最后,我们将元组转换为数组,以获得所需的输出格式。

你走在正确的轨道上,但你需要增加2而不是1。在获取第二个字符之前,还需要检查数组是否尚未结束,否则可能会遇到索引越界异常。试试我在下面写的代码。我试过了,效果很好。最好的

public static List<string> splitstring(string str)
{
List<string> result = new List<string>();
int strlen = str.Length;
for(int i = 0; i<strlen; i+=2)
{
string currentstr = str[i].ToString();
if (i + 1 <= strlen-1)
{ currentstr += str[i + 1].ToString(); }
result.Add(currentstr);
}
return result;
}

最新更新