2

I have file of such data:

  • 2016-07-01 - this is data
  • 39
  • 40
  • 36
  • 37
  • 40
  • 37

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");
        }
bengosha
  • 81
  • 2
  • 7
  • `Array.GetLength` returns the number of elements in the specified dimension. You have a `string[]` with only one dimension so this is useless. You can use `integerStrings.Length` – Tim Schmelter Jul 01 '16 at 08:00

7 Answers7

3

how about

List<int> Result = integerStrings.Select(x => x.Length).ToList();
fubo
  • 44,811
  • 17
  • 103
  • 137
1

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;
        }
Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78
1

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));
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

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());
Tran Anh Hien
  • 687
  • 8
  • 11
0

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"
Kahbazi
  • 14,331
  • 3
  • 45
  • 76
0
string[] contents = File.ReadAllLines(@"myfile.txt");
foreach(var line in contents)
{
  line.Length // this is your string length per line
}
0

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.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53