Home > Net >  C# add string without spaces into array
C# add string without spaces into array

Time:10-27

I have got:

string pattern = "ABCDEFGH!";

and i want to get it into array (pattern can be longer or shorter):

array[0] = A
array[1] = B
array[2] = C
//etc.

I have tried something like this:

help = "ABCDEFGH!"
string[] pattern = help.Split("");
            

First i wanted to add space between all signs and than split and add them to my array but maybe there is better idea.

CodePudding user response:

The following code will create an array of chars:

string pattern = "ABCDEFGH!";
char[] patternArray = pattern.ToCharArray();

CodePudding user response:

If you need an array of string you could try something likee this, but maybe there's a better way to do it.

string help = "ABCDEFGH!";
string[] patern = new string[help.Length];

for(int i = 0; i < help.Length; i  )
{
    patern[i] = help[i].ToString();
}

CodePudding user response:

Worth noting that C# allows use of the index operator on strings to get characters from the string as if it were a char array. If you only need to access, simply do that

string pattern = "ABCDEFGH!";
Console.WriteLine(pattern[0]); //prints "A"
Console.WriteLine(pattern[1]); //prints "B"
//...

//can use slice/range operators also
Console.WriteLine(pattern[0..2]); //prints "ABC"
Console.WriteLine(pattern[^1]); //prints "!" [^1] == [pattern.Length - 1]

If you need to save to a variable, use .ToCharArray() and you also access by index

char[] pattern = "ABCDEFGH!".ToCharArray();

Of course, in either case watch out for IndexOutOfBounds

  • Related