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");
        }
1
  • 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 Commented Jul 1, 2016 at 8:00

7 Answers 7

3

how about

List<int> Result = integerStrings.Select(x => x.Length).ToList();
Sign up to request clarification or add additional context in comments.

Comments

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;
        }

Comments

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));

Comments

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());

Comments

0
string[] contents = File.ReadAllLines(@"myfile.txt");
foreach(var line in contents)
{
  line.Length // this is your string length per line
}

Comments

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.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.