static void TEST(string arg)
{
string[] aArgs = new String[3];
aArgs = arg.Split(null,3);
}
我曾希望如果arg
只有两个项目,那么aArgs
在.Split
之后仍会有3个元素。但是,如果aArgs
找到2,则.Split
似乎被强制为2个元素。
如何将aArgs
保留为3个项目,.Split
是否为3。
此外,如果.Split
提交3件以上的物品,应该会发生什么?
答案 0 :(得分:3)
此代码将在您的问题中执行您要求的操作...索引3之后的任何值都将连接到最后一个值。
static void TEST(string arg)
{
string[] aArgs = new String[3];
string[] argSplit = arg.Split(null,3);
argSplit.CopyTo(aArgs, 0);
}
答案 1 :(得分:2)
这种方法怎么样:
static void TEST(String arg)
{
String[] mySA = SplitIntoArray(arg, 3, true); //truncating in this case to force 3 returned items
}
String[] SplitIntoArray(String StringToSplit, Int32 ArraySize, Boolean Truncate)
{
List<String> retList = new List<String>();
String[] sa = StringToSplit.Split(null);
if (sa.Length > ArraySize && Truncate)
{
for (Int32 i = 0; i < ArraySize; i++)
retList.Add(sa[i]);
}
else
{
foreach (String s in sa)
retList.Add(s);
}
return retList.ToArray();
}
这也可以很好地用作String扩展方法,只需稍作修改。
我想你也可以通过附加选项来增强它&gt;例如,ArraySize项目将所有内容组合到最后一项中,就像默认情况下那样。
答案 2 :(得分:0)
我不确定问题意图是什么,但是如果你想避免使用String.Split
方法分配数组,你应该使用@DonBoitnott建议的自定义代码:
var buffer = new string[3];
string testValue = "foo1;foo2;foo3;foo4;";
int count = Split(testValue, ';', buffer);
Debug.Assert(count == 3);
Debug.Assert(buffer[0] == "foo1" && buffer[1] == "foo2" && buffer[2] == "foo3;foo4;");
static int Split(string value, char separator, string[] buffer)
{
if (value == null)
return 0;
if (buffer == null || buffer.Length == 0)
throw new ArgumentNullException("buffer"); // or nameof(buffer) with c# 6 / .NET 4.6
const int indexNotFound = -1;
int bufferLength = buffer.Length;
int startIndex = 0;
int index;
int nextBufferIndex = 0;
while ((index = value.IndexOf(separator, startIndex)) != indexNotFound)
{
if (++nextBufferIndex == bufferLength)
{
buffer[nextBufferIndex-1] = value.Substring(startIndex);
break;
}
else
{
buffer[nextBufferIndex-1] = value.Substring(startIndex, index - startIndex);
startIndex = index + 1;
}
}
if (nextBufferIndex<bufferLength && value.Length >= startIndex)
buffer[nextBufferIndex++] = value.Substring(startIndex);
return nextBufferIndex;
}
请注意,预分配数组中的每个字符串都是一个新的字符串分配(String.Substring
分配一个新字符串)。