extracting sustrings from a string to array

  • 12 years ago


    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.


  • 12 years 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 ']'

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

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

  • 12 years 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).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match” - Bill Bryson