I need an array for a method to use to iterate through a string's characters and perform certain operations when one is found or found in certain combinations.

Anyway, to keep things separate and easier to interpret later, I have created an array of characters for the method to iterate through. This is how I have initialized the array:

    private char[] CharArray = new char[]
    {
        char.Parse("+"),
        char.Parse("("),
        char.Parse(")"),
        char.Parse("-"),
        char.Parse(" ")
    };

the array will always be the same, it shouldn't change unless there is an update to the software. Is this okay to do, or is there a better way to do this than parsing a bunch of strings?

Yes, just use single quote marks without the parse call. '+'
You can also call ToCharArray() on a full string.

private static char[] CharArray1 = { '+', '(', ')', '-', ' ' };
private static char[] CharArray2 = "+()- ".ToCharArray();

It looks like you're going to parse a phone number with an array like that, so I
made a practical example (with something extra):

using System;
using System.Text.RegularExpressions;

namespace DW_421823_CS_CON
{
   class Program
   {
      private static char[] CharArray1 = { '+', '(', ')', '-', ' ' };
      private static char[] CharArray2 = "+()- ".ToCharArray();
      static void Main(string[] args)
      {
         string strPhoneNumber = "+1-(913) 555-1212";

         Console.WriteLine(string.Join("", strPhoneNumber.Split(CharArray1, StringSplitOptions.RemoveEmptyEntries)));
         Console.WriteLine(string.Join("", strPhoneNumber.Split(CharArray2, StringSplitOptions.RemoveEmptyEntries)));
         Console.WriteLine(string.Join("", strPhoneNumber.Split("+()- ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)));
         Console.WriteLine(Regex.Replace(strPhoneNumber, "[^0-9]", ""));/*completely different*/
      }
   }
}

Edited 4 Years Ago by thines01

You can also treat a String as a character array, so

String charArray = "()+- ";

foreach (Char c in charArray) {
   ...

Is perfectly valid

Sorry I didn't reply earlier! I'm not getting email notices for articles anymore :(

Anyway, thanks for the help guys! I appreciate it!

This question has already been answered. Start a new discussion instead.