Community discussion forum

extracting sustrings from a string to array

  • 2 months ago

     Hi

    I want to extract sustrings from a string and want to store in an array.
    The string is dynamic it will change but the criteria to extract substring is same.
    say for example a string str="something is [!better] than [!nothing]"
    so i need to extract [!better] and [!nothing] from the string and store it in a string array, the string is dynamic it changes but i need to extract data between [ and ] including both the square brackets.
    If anybody can send any sample code, I will be very thankfull.
    Thanks

    Ansari

  • Advertisement

    Simply the fastest line-level profiler for .NET ever

    “The low overhead means it has minimal impact on the execution of my program”
    Mark Everest, Development Team Leader, Renault F1 Team Ltd.

    Try out the new ANTS Profiler 4 for yourself. Download your 14-day trial now

  • 2 months ago

    Hi Ansari,

    Put your string in 'str' and your parts will be in 'parts' List, at the end of the code :

    string str = "one [str1] two [str2]"; // strings in [] are parts
    List<string> parts = new List<string>(); // saves parts

    int start, // location of '['
        end = 0; // location of ']'
    while ((start = str.IndexOf('[',end)) != -1) // while there is another '[' in the string
    {
        end = str.IndexOf(']', start);
        if (end == -1) // if there is no ']'
            break;

        parts.Add(str.Substring(start, end-start+1)); // add current part
    }

    MessageBox.Show(parts[0]); // shows the first part

  • 2 months ago

     Jazakallah brother, Your code is very helpfull.

    Thanks a lot.

Post a reply

Enter your message below

Sign in or Join us (it's free).