Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. extracting sustrings from a string and store it in an array

extracting sustrings from a string and store it in an array

Scheduled Pinned Locked Moved C#
data-structurestutorial
14 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W Offline
    W Offline
    wajans
    wrote on last edited by
    #1

    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

    A D realJSOPR P G 5 Replies Last reply
    0
    • W wajans

      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

      A Offline
      A Offline
      Alan Balkany
      wrote on last edited by
      #2

      Look at String.IndexOf http://msdn.microsoft.com/en-us/library/system.string.indexof(VS.80).aspx[^] and String.Substring http://msdn.microsoft.com/en-us/library/system.string.substring(VS.80).aspx[^].

      1 Reply Last reply
      0
      • W wajans

        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

        D Offline
        D Offline
        DaveyM69
        wrote on last edited by
        #3

        string.Split method.

        string str = "something is [!better] than [!nothing]";
        string[] separators = new string[] { "[!better]", "[!nothing]" };
        string[] strArray = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        foreach (string item in strArray)
        {
        Console.WriteLine(item.Trim());
        }

        Edit: Just reread the question and you want the exact opposite! :-O :confused:

        Dave
        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
        Expect everything to be hard and then enjoy the things that come easy. (code-frog)

        1 Reply Last reply
        0
        • W wajans

          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

          realJSOPR Offline
          realJSOPR Offline
          realJSOP
          wrote on last edited by
          #4

          It would probably end up being a three-step process. If it's safe to assume that the stuff you're looking for would always be separated by a space, you could do this:

          string str = "something is [!better] than [!nothing]";
          // split the string on spaces
          string[] parts = str.Split(' ');
          List resultStringList = new List();

          foreach (string part in parts)
          {
          int pos1 = part.IndexOf("[");
          int pos2 = part.IndexOf("]");
          if (pos1 >= 0 && pos2 >= 0)
          {
          // get everything between the brackets, but NOT the brackets themselves
          string result = part.SubString(pos1+1, pos2);
          // add it to the list
          resultStringList.Add(result);
          }
          }

          string[] myResults = new string[resultStringList.Count];
          for (int i = 0; i < resultStringList.Count; i++)
          {
          myResults[i] = resultStringList[i];
          }

          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

          modified on Tuesday, September 16, 2008 10:23 AM

          W 1 Reply Last reply
          0
          • W wajans

            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

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #5

            Regular Expressions?

            1 Reply Last reply
            0
            • W wajans

              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

              G Offline
              G Offline
              Guffa
              wrote on last edited by
              #6

              How about a one-liner to extract the strings from the array using a regular expression and placing them in an array? :)

              string[] substrings = Regex.Matches(str, @"\[.*?\]").OfType<match>().Select(m => m.Value).ToArray();

              Despite everything, the person most likely to be fooling you next is yourself.

              modified on Tuesday, September 16, 2008 12:18 PM

              W 1 Reply Last reply
              0
              • G Guffa

                How about a one-liner to extract the strings from the array using a regular expression and placing them in an array? :)

                string[] substrings = Regex.Matches(str, @"\[.*?\]").OfType<match>().Select(m => m.Value).ToArray();

                Despite everything, the person most likely to be fooling you next is yourself.

                modified on Tuesday, September 16, 2008 12:18 PM

                W Offline
                W Offline
                wajans
                wrote on last edited by
                #7

                Hi Guffa Thanks for your reply. I am getting "Invalid expression term '>'" error. Please help resolve this issue. Thanks Ansari

                W L 2 Replies Last reply
                0
                • realJSOPR realJSOP

                  It would probably end up being a three-step process. If it's safe to assume that the stuff you're looking for would always be separated by a space, you could do this:

                  string str = "something is [!better] than [!nothing]";
                  // split the string on spaces
                  string[] parts = str.Split(' ');
                  List resultStringList = new List();

                  foreach (string part in parts)
                  {
                  int pos1 = part.IndexOf("[");
                  int pos2 = part.IndexOf("]");
                  if (pos1 >= 0 && pos2 >= 0)
                  {
                  // get everything between the brackets, but NOT the brackets themselves
                  string result = part.SubString(pos1+1, pos2);
                  // add it to the list
                  resultStringList.Add(result);
                  }
                  }

                  string[] myResults = new string[resultStringList.Count];
                  for (int i = 0; i < resultStringList.Count; i++)
                  {
                  myResults[i] = resultStringList[i];
                  }

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  modified on Tuesday, September 16, 2008 10:23 AM

                  W Offline
                  W Offline
                  wajans
                  wrote on last edited by
                  #8

                  Hi John I have a string which do not have spaces. Its something like this "

                  [!vDescription][!vDate]

                  [!vTitle]

                  ", Sorry to not mention it in my earlier post. Hope you will reply back with the solution. Thanks for your reply. Thanks Ansari

                  1 Reply Last reply
                  0
                  • W wajans

                    Hi Guffa Thanks for your reply. I am getting "Invalid expression term '>'" error. Please help resolve this issue. Thanks Ansari

                    W Offline
                    W Offline
                    wajans
                    wrote on last edited by
                    #9

                    Hi After doing r&d on regular expressions I got this answer. If we want to extract a word from a string like "[something]" We could use the Match method in the regular expression. Like this: string s = "

                    [!vDescription][!vDate]

                    [!vTitle]

                    "; Regex rx = new Regex(@"\[.*?\]"); Match mc = rx.Match(s); while(mc.Success) { Response.Write(mc.Value.ToString()); mc = mc.NextMatch(); } Thanks

                    G 1 Reply Last reply
                    0
                    • W wajans

                      Hi Guffa Thanks for your reply. I am getting "Invalid expression term '>'" error. Please help resolve this issue. Thanks Ansari

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10

                      You are probably not using framework 3.5 - Linq

                      1 Reply Last reply
                      0
                      • W wajans

                        Hi After doing r&d on regular expressions I got this answer. If we want to extract a word from a string like "[something]" We could use the Match method in the regular expression. Like this: string s = "

                        [!vDescription][!vDate]

                        [!vTitle]

                        "; Regex rx = new Regex(@"\[.*?\]"); Match mc = rx.Match(s); while(mc.Success) { Response.Write(mc.Value.ToString()); mc = mc.NextMatch(); } Thanks

                        G Offline
                        G Offline
                        Guffa
                        wrote on last edited by
                        #11

                        Use the Matches method to get them all:

                        MatchCollection matches = Regex.Matches(s, "\[.*?\]");
                        string substrings[] = new string[Matches.Count];
                        for (int i = 0; i < matches.Count; i++) {
                        substrings[i] = matches[i].Value;
                        }

                        Despite everything, the person most likely to be fooling you next is yourself.

                        W 1 Reply Last reply
                        0
                        • G Guffa

                          Use the Matches method to get them all:

                          MatchCollection matches = Regex.Matches(s, "\[.*?\]");
                          string substrings[] = new string[Matches.Count];
                          for (int i = 0; i < matches.Count; i++) {
                          substrings[i] = matches[i].Value;
                          }

                          Despite everything, the person most likely to be fooling you next is yourself.

                          W Offline
                          W Offline
                          wajans
                          wrote on last edited by
                          #12

                          Hi Guffa My requirement changed, I am sure you can help me. I have a string for example str="something [!str1] and something [!str2].." so I want to store the substring from start up till "[" and then from "[" to "]" and so on. so how can we achieve it. Thanks Ansari

                          G 1 Reply Last reply
                          0
                          • W wajans

                            Hi Guffa My requirement changed, I am sure you can help me. I have a string for example str="something [!str1] and something [!str2].." so I want to store the substring from start up till "[" and then from "[" to "]" and so on. so how can we achieve it. Thanks Ansari

                            G Offline
                            G Offline
                            Guffa
                            wrote on last edited by
                            #13

                            Split on brackets, then you get an array containing the strings between the brackets. string str="something [!str1] and something [!str2] else."; string[] substrings = str.Split(new char[]{ '[', ']' }); This gives you an array with the following strings: "something " "!str1" " and something " "!str2" " else."

                            Despite everything, the person most likely to be fooling you next is yourself.

                            W 1 Reply Last reply
                            0
                            • G Guffa

                              Split on brackets, then you get an array containing the strings between the brackets. string str="something [!str1] and something [!str2] else."; string[] substrings = str.Split(new char[]{ '[', ']' }); This gives you an array with the following strings: "something " "!str1" " and something " "!str2" " else."

                              Despite everything, the person most likely to be fooling you next is yourself.

                              W Offline
                              W Offline
                              wajans
                              wrote on last edited by
                              #14

                              Thanks a lot Guffa for your quick reply. It works great.

                              modified on Friday, September 19, 2008 5:54 AM

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups