计算数组中2个元素之间的元素 [英] Count the elements between 2 elements in an Array

查看:111
本文介绍了计算数组中2个元素之间的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!
请帮助我计算2个元素之间的元素数.
例如,我有一个像这样的字符串数组:

Hi !
Please help me counting the number of elements between 2 elements.
For example I have a string array like this :

<br />
int[] number = new int[]{1,2,3,4,5};<br />



我希望代码返回我3(介于1和5之间的2、3、4)

我在Google周围呆了一会儿,但没有发现与此问题相关的任何信息.
谢谢.



And I expect the code return me 3 (2,3,4 between 1 & 5)

I''ve fool around Google for a while but I found nothing related to this problem.
Thank you.

推荐答案

您将不会为此找到Google结果.

这很像是一项家庭作业,因此,您不会从我们那里为您编写代码.

这很容易做到.至少需要一个循环,一个计数器和一个if语句.
You won''t find a Google result for this.

This reeks of being a homework assignment, and as such, you won''t get code from us written for you.

It''s ridiculously easy to do. At a bare minimum, you need some kind of loop, a counter, and an if statement.


好.
我找到了解决方案,在这种情况下它更易于处理.
对于某天可能需要它的人.


Ok.
I found out a solution to this, it''s simpler to handle in this case.
For someone may need it in someday.


public void DoCount()
{
    string k = ",";
    // Read the file lines into a string array.
    string[] readlines = File.ReadAllLines(fname);
    // Move into List for handling easier
    List<string> read = new List<string>();
    read.AddRange(readlines);
    // Insert one semicolon into the first index
    read.Insert(0, k);
    // For counting
    int count = 0;
    // An other List to add the number of count
    List<int> result = new List<int>();
    // Loop and count
    for (int i = 0; i < read.Count; i++)
    {
        // If the element is not a semicolon, count it
        if (read[i].ToString() != k)
        {
            count++;
        }
        // If it is, get the number of count
        else
        {
            result.Add(count);
            // Reset count
            count = 0;
        }
    }
}



最好的问候.
//非常抱歉我的英文xD错误



Best regards.
// So sorry cuz of my bad English xD


int[] items = new int[] { 1, 2, 3, 2, 7, 4, 2, 8, 9, 1, 2, 10, 11, 3, 4, 10 };
int k = 10, l = 2;
int first =k, second = l;
List<int> between = new List<int>();
for (int i = 0; i < items.Length; i++)
{
    if(items[i] == k)
    {
        first = k;
        second = l;
    }
    if (items[i] == l)
    {
        first = l;
        second = k;
    }
    if (items[i] == first)
        if (i - 1 < items.Length)
            for (int j = i + 1; j < items.Length; j++)
            {
                if (items[j] == second)
                {
                    between.Add(j - i -1);
                }
            }
}



k l:是您的2个数字

between:是一个返回您的值的列表.



k , l : are your 2 numbers

between : is a list that returns your values.


这篇关于计算数组中2个元素之间的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆