在二维 char 数组中条件声明数组?
我有一个用四个字符串声明的二维字符数组。
private static string string1 = "abcde";
private static string string2 = "ABCDE";
private static string string3 = "12345";
private static string string4 = "67890";
public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
char[][] charGroups = new char[][]
{
string1.ToCharArray(),
string2.ToCharArray(),
string3.ToCharArray(),
string4.ToCharArray()
};
}
我想声明并初始化数组,以便字符串添加是基于四个布尔标志的条件。例如,如果 includeOne 和 includeThree 为 true,我希望最终得到一个使用了 string1 和 string 3 的 charGroup[2][5]。
(这是现有代码,我不想从根本上更改其余代码如果我可以有条件地在该块中声明数组,我就完成了。)
I have a two-dimensional char array declared with four strings.
private static string string1 = "abcde";
private static string string2 = "ABCDE";
private static string string3 = "12345";
private static string string4 = "67890";
public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
char[][] charGroups = new char[][]
{
string1.ToCharArray(),
string2.ToCharArray(),
string3.ToCharArray(),
string4.ToCharArray()
};
}
I want to declare and initialize the array such that the string add is conditional based on four bool flags. For example, if includeOne and includeThree are true, I want to end up with a charGroup[2][5] having used string1 and string 3.
(This is existing code where I don't want to radically change the rest of the code. if I can conditionally declare the array in that block, I'm done.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要的方式就像一个列表,所以最好通过列表实现它,然后通过
ToArray
返回一个数组:The manner you want is like a list, so it's better implement it by list and then return an array by
ToArray
:我没有虚拟机,但我认为这应该可以工作...
如果您想要做的只是将字符串作为字符数组包含在设置了各自的标志的情况下,那么我认为这可以解决问题。它使用条件运算符来包含“:”的左侧(如果 includeX 为 true),否则包含右侧。
I don't have the VM going but I think this should work...
If all you want to do is include the string as a character array if their respective flag is set then I think this will do the trick. It is using the conditional operator to include the left side of ':' (if includeX is true) otherwise include the right side.
1) 计算需要添加多少个字符串(有多少个标志为 true)。
2)
char[][] charGroups = new char[count][];
(可能需要是char[][count]
;我正在操作很少的sleep)3) 将索引初始化为0;对于每个标志(如果已设置),请将适当的 char[] 放入该索引中,并递增索引。
但是为什么,哦,为什么你要把
String
分成char[]
呢?String
类是你的朋友。它想让您的生活更轻松。1) Count up how many strings need to be added (how many of the flags are true).
2)
char[][] charGroups = new char[count][];
(might need to bechar[][count]
; I'm operating on very little sleep)3) Init an index to 0; for each flag, if it's set, put the appropriate
char[]
into that index, and increment the index.But why, oh why are you taking the
String
s apart intochar[]
s? TheString
class is your friend. It wants to make your life easier.