Jump to content

How would YOU do this?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
williamevanl

williamevanl

    Learning Programmer

  • Members
  • PipPipPip
  • 61 posts
I'm converting a bunch of code in R to c#. I keep coming across line of code like:


b.bracket = gegexpr("\\[", ped)[[1]]
this basically just creates an array in b.bracket that holds the index positions of all '[' in a string.

I also come across this sort of thing:
some.index = b.bracket[b.bracket > 0]

this creates an array in some.index with all values of b.bracket that are greater then zero.

my question: is there an efficient way to code this in C#? My code seems to contain a ridiculous amount of looping and inefficiency:
 List<int> l_bracket_index_numbers = new List<int>();


            for (count_incidents_S = 0; count_incidents_S < (len); count_incidents_S++)

            {

                symbol_index = new_ped.IndexOf(lbracket, count_incidents_S);

                if (symbol_index != -1)                                                     //last character 

                {

                    l_bracket_index_numbers.Add(symbol_index);

                }

            }

            List<int> l_bracket_index_numbers_nd = l_bracket_index_numbers.Distinct().ToList();

            Final_Result_lb = l_bracket_index_numbers_nd;


#2
Matt Ellen

Matt Ellen

    Newbie

  • Members
  • PipPip
  • 14 posts
There is a simple way to do this using linq:

string test = "[this [ is [ a [ string [ with left square brackets in.";

var ps = test.Select((c, i) => c == '[' ? i : -1).Where(i => i != -1);
That will get you your first array, albeit as an IEnumerable<int>. If you want it as an array, simply call the ToArray() extension method.

Essentially what it says is, "build me a list by examining the string. For every '[' put its position in the string in the list and for all other characters put in -1, then filter out all the -1 entries."

To get your second array, simply change the where clause:

.Where(i => i >0);
That will get you all the left square brackets that aren't at the start of the string.

I'm sure there is a way to do this with regex, but that's not my strong point.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users