tags:

views:

108

answers:

3

How can I append strings to an array if a certain checkbox is true?

//Create an array to hold the values.
string[] charArray;

if (abc.Checked == true)
{
    //append lowercase abc
}

if (a_b_c.Checked == true)
{
    //append uppercase abc
}

if (numbers.Checked == true)
{
    //append numbers
}

if (symbols.Checked == true)
{
    //append symbols
}
+8  A: 

You typically don't want to try appending to an array in .NET. It can be done, but it's expensive. In this case, you want to use a StringBuilder

Example:

StringBuilder sb = new StringBuilder();

if (abc.Checked)
{
    //append lowercase abc
    sb.Append(textbox1.Text.ToLower());
}

When you're done, you can get the string by calling sb.ToString(), or get the characters by calling sb.CopyTo().

Naming an array of strings "charArray" is very confusing.

Or are you trying to append strings, not append characters to a string? You want to use a List<string> for that, rather than a string[].

Example:

List<string> strings = new List<string>();

if (abc.Checked)
{
    // append lowercase abc
    strings.Add(textbox1.Text.ToLower());
}
Jim Mischel
point in having == true is?
Blam
== true is not required
Yogendra
`sb.Append(textbox1.Text.ToLower());` What if I wanted to append multiple values. Like the whole alphabet?
jeez chill with the ==true hating. I leave it because I like it for clarity.
+2  A: 

Hi shorty,

why don't you append strings to List, and then convert it to array?

muek
var list = new List<string>(); list.Add("any string"); var a = list.ToArray();
Rony
+2  A: 

An array by definition has a fixed size. If telling your strings apart is important for you, and/or you want to be able to iterate over them, sort them, etc. - use a StringCollection or another better suited collection. If you just want to append a string to another string, use StringBuilder, as Jim said.

Oren A