Reputation: 47
I'm now doing a project about solving a Magic cube problem. I want to create an array to remember the steps like this:
char[] Steps = new char[200];
Each time I do the 'F','B','R','L','U','D' turn method, it will add a 'F','B','R','L','U','D' character in the array. But when I want to get the length of the steps, it always shows 200.
for example:
char[] steps = new char[5];
and now I've already added 3 steps:
steps[] = {'f','b','f','',''};
How can I get the length '3'?
Or is there any alternative method I can use that I don't need to set the length at the beginning?
Upvotes: 0
Views: 1927
Reputation: 13794
you can just use List<char>
but if performance is really critical in your sceanario you can just initialize the initial capacity
something like the following
List<char> list = new List<char>(200);
list.Add('c');
list.Add('b');
here count will return just what you have really added
var c = list.Count;
note in list you can apply Linq Count()
or just use the Count
property which does not need to compute like Linq
and return the result immediately
Upvotes: 3
Reputation: 823
you could use a list of character that would make things a lot simpler like this :
List<char> steps = new List<char>();
and just add a line to the list for each steps :
char move = 'F';
steps.add(move);
finally then you can count the number of move in the list easily
int numberofmove = steps.count();
Upvotes: 0
Reputation: 4981
To count non-empty items using System.Linq
:
steps.Count(x => x != '\0');
Your code doesn't compile since ''
isn't allowed as a char
, but I'm assuming that you mean empty elements in a char
array which are actually represented by '\0'
or the Unicode Null. So the above condition simply counts the non null items in your array.
Upvotes: 0
Reputation: 7706
You will get compilation error on this line
steps[] = {'f','b','f','',''};
As you cannot use empty char and you need to write steps instead of steps[]. I will suggest you to use string array instead and using LINQ get count of not empty elements in this way:
string [] steps = {"f","b","f","",""};
Console.WriteLine(steps.Where(x=>!string.IsNullOrEmpty(x)).Count());
Upvotes: 2