0

I have a file containing rows with pipe (|) in column delimiter, I want to find the infomation between the 99th and 100th delimiters. The row has been read into my string variable such as string str = @"1|2|a|||....|||abc|d|...." and I want to find and store the abc value in my another variable.

is there any neat way, such as using Regex, to make the solution work? It seems too stupid to loop 100 times using something like substring.

a4194304
  • 366
  • 2
  • 13
  • 2
    `string.split("|")[99]` not tested but should be close enough – phuzi Aug 21 '19 at 09:42
  • You can use skip(99) – jdweng Aug 21 '19 at 09:44
  • 1
    You can adapt this answer: https://stackoverflow.com/a/187394/2956272. Still, the most efficient solution is just a loop with indexof (you can supply a starting position as a parameter) –  Aug 21 '19 at 09:45

4 Answers4

2

Don't use a regular expression just because you can. It's usually far easier to not use them in most circumstances.

Instead you should use the built in operators and do something like:

str.split("|")[99];

Not tested but should be close enough for you to get what you want

phuzi
  • 12,078
  • 3
  • 26
  • 50
1

You can use String.Split to split the string into an array and then access it via index:

var arr = str.Split('|');
var yourOtherVariable = arr[99];
0

you can use the below method also, logic is to get the substring from start position of delimiter till the next position of the delimiter.

string newString = "";
int position = m;
string delimeter = "|";
int start = IndexOfNth(str, delimeter , m);
if (start < 0)
    return;
int end = IndexOfNth(str.Substring(start + 1), delimeter, 1);

if (end < 0)
    newString = str.Substring(start);

newString = str.Substring(start, end + 1);


public static int IndexOfNth(string str, string value, int nth = 1) {
    if (nth <= 0)
        throw new ArgumentException("cannot be less than zero");
    int offset = str.IndexOf(value);
    for (int i = 1; i < nth; i++) {
        if (offset == -1) return -1;
        offset = str.IndexOf(value, offset + 1);
    }
    return offset;
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

Same as phuzi, but as a function that could be in a C# utility class:

public static string GetSubString(string str, string delimiter, Int32 index)
        {
            if (str == null) return "";
            try
            {
                return str.Split(delimiter)[index];
            }
            catch
            {
                if (index == 0) return str;
                return string.Empty;
            }
        }

Also see: Get the nth string of text between 2 separator characters

mike g
  • 41
  • 4