Reputation: 81
I have file of such data:
I want to count each elements in my array. For example: 10, 2, 2, 2, 2, 2, 2. How do that?
string FilePath = @"path";
int counteachelement = 0;
string fileContent = File.ReadAllText(FilePath);
string[] integerStrings = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int n = 0; n < integerStrings.Length; n++)
{
counteachelement = integerStrings.GetLength(n);
Console.Write(counteachelement + "\n");
}
Upvotes: 2
Views: 5197
Reputation: 747
You can use javascript:
var arr=["39","9","139"];
var temp="";
for(i=0;i<arr.length;i++)
temp += (arr[i].length) + ", ";
alert("Lenght element array: " +temp.toString());
Upvotes: 1
Reputation: 14995
You can use Linq
to do this
List<string> list = new List<string>();
list.Add("39");
list.Add("40");
list.Add("36");
list.Add("37");
list.Add("40");
list.Add("37");
list.Add("39");
var output = list.Select(i => i.Length);
Console.WriteLine(string.Join(" ",output));
//"2 2 2 2 2 2 2"
Upvotes: 0
Reputation: 4606
Here I have modified your code to get the count of each element inside the for loop that you are using-
string FilePath = @"path";
int counteachelement = 0;
string fileContent = File.ReadAllText(FilePath);
string[] integerStrings = fileContent.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
int count = 0;
for (int n = 0; n < integerStrings.Length; n++)
{
count = integerStrings[n].Length;
}
Upvotes: 1
Reputation: 109537
You can use File.ReadLines()
to avoid holding all the lines in memory at once, and then simply use Enumerable.Select()
to pick out the length of each line. (This assumes that you are not ignoring or do not have any blank lines):
var lengths = File.ReadLines(FilePath).Select(s => s.Length);
Console.WriteLine(string.Join("\n", lengths));
Upvotes: 1
Reputation: 25527
You can do,
var str = "2016-07-01 - this is data,39,40,36,37,40,37,";
var Result = str.Split(',').Select(p => p.Count()).ToList();
Note: I am considering your input as comma separated values.
Upvotes: 0
Reputation:
string[] contents = File.ReadAllLines(@"myfile.txt");
foreach(var line in contents)
{
line.Length // this is your string length per line
}
Upvotes: 0
Reputation: 45947
how about
List<int> Result = integerStrings.Select(x => x.Length).ToList();
Upvotes: 3