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. The Lounge
  3. Coding Challenge

Coding Challenge

Scheduled Pinned Locked Moved The Lounge
c++architecturehelp
165 Posts 47 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.
  • C Chris Maunder

    Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

    M Offline
    M Offline
    mattiek77
    wrote on last edited by
    #116

    Mix of recursion and regex

    using System;
    using System.Text.RegularExpressions;
    namespace CPTrimmer
    {
    class Program
    {
    static void Main(string[] args)
    {
    string startVal = "dog cat monkey dog horse dog";
    string[] toTrim = { "dog", "cat" };
    Stripper(ref startVal, toTrim);
    Console.WriteLine(startVal);
    Console.ReadLine();
    }
    static void Stripper(ref string input, string[] toTrim)
    {
    foreach (string trimVal in toTrim)
    {
    Regex start = new Regex(@"\A[ ]{0,}"+trimVal);
    if (start.IsMatch(input))
    {
    input = start.Replace(input, "");
    Stripper(ref input, toTrim);
    }
    Regex end = new Regex(trimVal + @"[ ]{0,}\Z");
    if (end.IsMatch(input))
    {
    input = end.Replace(input, "");
    Stripper(ref input, toTrim);
    }
    }
    }
    }
    }

    1 Reply Last reply
    0
    • M Marc Clifton

      Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      namespace Stripper
      {
      public enum StringPoint
      {
      None,
      Start,
      End,
      }
      public static class StringHelpersExtensions
      {
      public static string RightOf(this String src, string s)
      {
      string ret = src;
      int idx = src.IndexOf(s);
      if (idx != -1)
      {
      ret = src.Substring(s.Length);
      }
      return ret;
      }
      public static string LeftOfRightmostOf(this String src, string s)
      {
      string ret = src;
      int idx = src.LastIndexOf(s);
      if (idx != -1)
      {
      ret = src.Substring(0, idx);
      }
      return ret;
      }
      public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
      {
      bool ret = false;
      whichEnd = StringPoint.None;
      match = String.Empty;
      foreach (string item in items)
      {
      if (src.StartsWith(item))
      {
      match = item;
      whichEnd = StringPoint.Start;
      ret = true;
      break;
      }
      if (src.EndsWith(item))
      {
      match = item;
      whichEnd = StringPoint.End;
      ret = true;
      break;
      }
      }
      return ret;
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      string input = "dog cat monkey dog horse dog";
      string[] stripOf = { "dog", "cat" };
      string desiredOutput = " monkey dog horse ";
      string result = Stripper(input, stripOf);
      if (result == desiredOutput)
      {
      Console.WriteLine("Success");
      }
      else
      {
      Console.WriteLine("Fail! '" + result + "'");
      }
      }
      static string Stripper(string input, string[] stripOf)
      {
      string ret = input;
      string match;
      StringPoint whichEnd;
      string test = ret.Trim();
      string leftPad = String.Empty;
      string rightPad = String.Empty;
      while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
      {
      switch (whichEnd)
      {
      case StringPoint.Start:
      // The result always preserves the leading space separating the token, so add it back in.
      leftPad = " ";
      ret = leftPad + test.RightOf(match).Trim() + rightPad;
      break;
      case StringPoint.End:
      // The result always preserves

      C Offline
      C Offline
      Chris Maunder
      wrote on last edited by
      #117

      Quote:

      There's probably a regex solution

      result = Regex.Replace("dog cat monkey dog horse dog", "^(dog|cat)*(.*?)((dog|cat)*)$", "$2",
      RegexOptions.IgnoreCase | RegexOptions.SingleLine);

      cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

      M 1 Reply Last reply
      0
      • C Chris Maunder

        Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #118

        Assuming strings contain chars below Unicode 32000 only, and ignoring white space details:

        string[] drops=new string[]{"cat","dog"};
        string s="dog cat monkey dog horse dog";
        string rep=" ";
        char c=(char)32000;
        foreach(string drop in drops) {s=s.Replace(drop,c.ToString()); rep+=c; c++;}
        s=s.Trim(rep.ToCharArray());
        c=(char)32000;
        foreach(string drop in drops) {s=s.Replace(c.ToString(),drop); c++;}
        log(s);

        :zzz:

        Luc Pattyn [My Articles] Nil Volentibus Arduum

        C 1 Reply Last reply
        0
        • L Luc Pattyn

          Assuming strings contain chars below Unicode 32000 only, and ignoring white space details:

          string[] drops=new string[]{"cat","dog"};
          string s="dog cat monkey dog horse dog";
          string rep=" ";
          char c=(char)32000;
          foreach(string drop in drops) {s=s.Replace(drop,c.ToString()); rep+=c; c++;}
          s=s.Trim(rep.ToCharArray());
          c=(char)32000;
          foreach(string drop in drops) {s=s.Replace(c.ToString(),drop); c++;}
          log(s);

          :zzz:

          Luc Pattyn [My Articles] Nil Volentibus Arduum

          C Offline
          C Offline
          Chris Maunder
          wrote on last edited by
          #119

          :thumbsup: Neat, but lots and lots of new objects created.

          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

          1 Reply Last reply
          0
          • M Marc Clifton

            You're algorithm results in: "  monkey dog horse " (two leading spaces) rather than: " monkey dog horse " It's really odd how every solution that I've seen somehow fails to take this into account (as well as the fact that after the first trim, there will be a leading or trailing space in the result.) Are we that bad at reading specs, meeting simple requirements, and testing our code? :sigh: Marc

            My Blog
            An Agile walk on the wild side with Relationship Oriented Programming

            K Offline
            K Offline
            Karl Sanford
            wrote on last edited by
            #120

            Chris updated the guidance, and I have changed my solution accordingly.

            Be The Noise

            1 Reply Last reply
            0
            • C Chris Maunder

              Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

              B Offline
              B Offline
              BillWoodruff
              wrote on last edited by
              #121

              private string inS = "dog cat monkey dog horse dog";

              private List<string> rmS = new List<string> {"dog", "cat"};

              private string finalString = "";

              private string resultString = " ";

              private string removeVarious(string iStr, List<string> iListStr)
              {
              for (int i = 0; i < iListStr.Count; i++)
              {
              string str = iListStr[i];

                  if (iStr.StartsWith(str))
                  {
                      iStr = iStr.Remove(0, str.Length + 1);
                      finalString = iStr;
                  }
              
                  if (iStr.EndsWith(str))
                  {
                      iStr = iStr.Remove(iStr.Length - str.Length - 1, str.Length + 1);
                      finalString = iStr;
                  }
              
                  if (iListStr.Count > 0)
                  {
                      iListStr.RemoveAt(0);
                      // recursion here
                      removeVarious(iStr, iListStr);
                  }
                  else
                  {
                      break;
                  }
              }
              
              return resultString.Insert(1, finalString);
              

              }

              Note: this was written before Chris changed the accepted output to include the word "cat" at the beginning. Meow. best, Bill

              "It is the mark of an educated mind to be able to entertain a thought without accepting it." Aristotle

              1 Reply Last reply
              0
              • C Chris Maunder

                Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                S Offline
                S Offline
                Slacker007
                wrote on last edited by
                #122

                my $trimWord = "dog";
                my $string = "dog cat monkey dog horse dog";

                $string =~ s/^($trimWord)+|($trimWord)+$//g;

                print $string;

                Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
                "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)

                1 Reply Last reply
                0
                • N NormDroid

                  Shit my eyes are bleeding :)

                  Software Kinetics Wear a hard hat it's under construction
                  Metro RSS

                  S Offline
                  S Offline
                  Slacker007
                  wrote on last edited by
                  #123

                  You shat your eyes or your eyes are bleeding? :laugh: :-D :thumbsup:

                  Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
                  "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)

                  1 Reply Last reply
                  0
                  • C Chris Maunder

                    Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                    C Offline
                    C Offline
                    CPallini
                    wrote on last edited by
                    #124

                    The function:

                    -- function
                    require("lpeg")
                    d = lpeg.P"dog" + lpeg.P"cat"
                    g = d^0 * lpeg.C((1-d)^1 * (d^0 * (1-d))^0) * d^0
                    function trm(s) return lpeg.match(g, s) or "" end

                    the test:

                    -- test
                    t = {
                    "dog cat monkey dog horse dog",
                    "dogcatmonkeycatcatcat",
                    "dog",
                    "doghorsedogdog dog",
                    "monkey",
                    "catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat"
                    }

                    for i,v in ipairs(t) do
                    print ("'" .. v .. "'" .. " -> " .. "'" .. trm(v) .. "'")
                    end

                    the output:

                    'dog cat monkey dog horse dog' -> ' cat monkey dog horse '
                    'dogcatmonkeycatcatcat' -> 'monkey'
                    'dog' -> ''
                    'doghorsedogdog dog' -> 'horsedogdog '
                    'monkey' -> 'monkey'
                    'catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat' -> 'horse sheep dog cat pig horse sheepcatmonkey'

                    If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                    This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                    [My articles]

                    1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      I have discovered a truly marvellous solution of this, which the margin of this website is too narrow to contain.

                      Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

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

                      I bet that's the last programming challenge you try!

                      MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                      1 Reply Last reply
                      0
                      • C Chris Maunder

                        Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                        cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

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

                        Chris Maunder wrote:

                        Given a string of text, trim from each end of the text each all occurrences of a given set of strings

                        Assuming (from your sample) you only want to remove a single item from each end (hence the leading 'cat' remains), then the below would seem to provide the requisite output and I feel earn bonus points for its simplicity, elegance and the fact that it's the first opportunity I've had to do c# for nearly a year!

                        private string CodingChallenge(string source, string[] removals)
                        {
                        string delimiter = " ";
                        bool leftDone = false;
                        bool rightDone = false;

                                foreach (string s in removals)
                                {
                                    if (!leftDone && source.Substring(0, s.Length) == s && source.Substring(s.Length, 1) == delimiter)
                                    {
                                        source = source.Substring(s.Length);
                                        leftDone = true;
                                    }
                        
                                    if (!rightDone && source.Substring(source.Length - s.Length) == s && source.Substring(source.Length - s.Length - 1, 1) == delimiter)
                                    {
                                        source = source.Substring(0, source.Length - s.Length);
                                        rightDone = true;
                                    }
                                }
                        
                                return source;
                            }
                        

                        MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                        1 Reply Last reply
                        0
                        • C Chris Maunder

                          Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                          E Offline
                          E Offline
                          ErnestoNet
                          wrote on last edited by
                          #127

                          Need to check this with other strings, debug some more, improve comments and string handling in main(), etc. But still....here it goes:

                          #include "stdafx.h"

                          const wchar_t whitechar = ' ';
                          const bool IncludeWhiteSpace = true;
                          const wchar_t* wordstoremove[] = {L"dog", L"cat"};

                          const wchar_t* strtoparse = L"dog cat monkey dog horse dog"; //Len 28
                          int ltoparse;
                          const int numwords = 2;

                          int wordlen[numwords];

                          //Positions in the original string to rip
                          int pos_orig_from;
                          int pos_orig_to;

                          //Len of left and right copies
                          int left_len;
                          int right_len;

                          //Gets hoy many bytes per char
                          void ProcessLeft(wchar_t* strresult)
                          {
                          bool bContinue = true;

                          pos\_orig\_from = left\_len = 0;
                          
                          while (bContinue)
                          {
                          	//Check for whitespaces. If there are, copy them
                          	if (strtoparse\[pos\_orig\_from\] == whitechar)
                          	{
                          		pos\_orig\_from ++;
                          		if (IncludeWhiteSpace)
                          		{
                          			strresult\[left\_len\] = whitechar;
                          			left\_len ++;
                          		}
                          	}
                          	else
                          	{
                          		bContinue = false;
                          		for (int i = 0; i < numwords; i++)
                          		{
                          			//Compare strings
                          			wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_from;
                          			if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0)
                          			{
                          				pos\_orig\_from += wordlen\[i\];
                          				bContinue = true;
                          				break;
                          			}
                          		}
                          	}
                          }
                          

                          }
                          void ProcessRight(wchar_t* strresult)
                          {
                          bool bContinue = true;

                          pos\_orig\_to = right\_len = ltoparse - 1;
                          
                          while (bContinue)
                          {
                          	//Check for whitespaces. If there are, copy them
                          	if (strtoparse\[pos\_orig\_to\] == whitechar && IncludeWhiteSpace)
                          	{
                          		pos\_orig\_to -= 1;
                          		if (IncludeWhiteSpace)
                          		{
                          			strresult\[right\_len\] = whitechar;
                          			right\_len -= 1;
                          		}
                          	}
                          	else
                          	{
                          		bContinue = false;
                          		for (int i = 0; i < numwords; i++)
                          		{
                          			//Compare strings
                          			//To check right, start from end and substract string to compare len
                          			wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_to - wordlen\[i\] + 1;
                          			if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0)
                          			{
                          				pos\_orig\_to -= wordlen\[i\];
                          				bContinue = true;
                          				break;
                          			}
                          		}
                          	}
                          }
                          

                          }

                          int _tmain(int argc, _TCHAR* argv[])
                          {

                          //Load len of words to avoid rechecking
                          for (int i=0; i
                          
                          1 Reply Last reply
                          0
                          • M Marc Clifton

                            Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:

                            using System;
                            using System.Collections.Generic;
                            using System.Linq;
                            using System.Text;
                            namespace Stripper
                            {
                            public enum StringPoint
                            {
                            None,
                            Start,
                            End,
                            }
                            public static class StringHelpersExtensions
                            {
                            public static string RightOf(this String src, string s)
                            {
                            string ret = src;
                            int idx = src.IndexOf(s);
                            if (idx != -1)
                            {
                            ret = src.Substring(s.Length);
                            }
                            return ret;
                            }
                            public static string LeftOfRightmostOf(this String src, string s)
                            {
                            string ret = src;
                            int idx = src.LastIndexOf(s);
                            if (idx != -1)
                            {
                            ret = src.Substring(0, idx);
                            }
                            return ret;
                            }
                            public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
                            {
                            bool ret = false;
                            whichEnd = StringPoint.None;
                            match = String.Empty;
                            foreach (string item in items)
                            {
                            if (src.StartsWith(item))
                            {
                            match = item;
                            whichEnd = StringPoint.Start;
                            ret = true;
                            break;
                            }
                            if (src.EndsWith(item))
                            {
                            match = item;
                            whichEnd = StringPoint.End;
                            ret = true;
                            break;
                            }
                            }
                            return ret;
                            }
                            }
                            class Program
                            {
                            static void Main(string[] args)
                            {
                            string input = "dog cat monkey dog horse dog";
                            string[] stripOf = { "dog", "cat" };
                            string desiredOutput = " monkey dog horse ";
                            string result = Stripper(input, stripOf);
                            if (result == desiredOutput)
                            {
                            Console.WriteLine("Success");
                            }
                            else
                            {
                            Console.WriteLine("Fail! '" + result + "'");
                            }
                            }
                            static string Stripper(string input, string[] stripOf)
                            {
                            string ret = input;
                            string match;
                            StringPoint whichEnd;
                            string test = ret.Trim();
                            string leftPad = String.Empty;
                            string rightPad = String.Empty;
                            while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
                            {
                            switch (whichEnd)
                            {
                            case StringPoint.Start:
                            // The result always preserves the leading space separating the token, so add it back in.
                            leftPad = " ";
                            ret = leftPad + test.RightOf(match).Trim() + rightPad;
                            break;
                            case StringPoint.End:
                            // The result always preserves

                            P Offline
                            P Offline
                            Pete OHanlon
                            wrote on last edited by
                            #128

                            Your former client base is showing mate - calling a method Stripper.

                            Forgive your enemies - it messes with their heads

                            "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                            My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                            M 1 Reply Last reply
                            0
                            • C Chris Maunder

                              Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                              cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                              A Offline
                              A Offline
                              AnthonyN1974
                              wrote on last edited by
                              #129

                              I was fed up, so here it is in c#

                              using System;
                              using System.Collections.Generic;
                              using System.Linq;
                              using System.Text;

                              namespace CodeChallenge
                              {
                              class Program
                              {
                              private static List<string> wordsToRemove = new List<string>() { "dog", "cat" };

                              static void Main(string\[\] args)
                              {
                                string text = "dog cat monkey dog horse dog";
                              
                                string\[\] words = text.Split(' ');
                                string\[\] output;
                                int start = 0;
                                int end = 0;
                              
                                // test the start
                                if (wordsToRemove.Contains(words\[0\]) && words.Length > 0)
                                  start = 1;
                              
                                // test the end
                                if (wordsToRemove.Contains(words\[words.Length - 1\]) && words.Length != start)
                                  end = (words.Length - 1) - start;
                                else
                                  end = words.Length - start;
                              
                                //build
                                output = new string\[end\];
                                Array.Copy(words, start, output, 0, end);
                              
                                //output
                                Console.WriteLine(string.Join(" ",output));
                              }
                              

                              }
                              }

                              1 Reply Last reply
                              0
                              • C Chris Maunder

                                Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                M Offline
                                M Offline
                                mrchief_2000
                                wrote on last edited by
                                #130

                                Probably not the most efficient, but in C#, this works:

                                using System.Text.RegularExpressions;

                                var source = "dog cat dog horses monkeys dog";
                                var stringsToTrim = new[] { "dog", "cat" };
                                var trimmedString = Regex.Replace(source, string.Format("^({0})|({0})$", string.Join("|", stringsToTrim )), "");
                                Console.WriteLine(trimmedString);

                                Live demo: http://rextester.com/GTLWO64640[^] Making above shorter:

                                using System.Text.RegularExpressions;

                                Console.WriteLine(Regex.Replace("dog cat dog horses monkeys dog", string.Format("^({0})|({0})$", string.Join("|", "dog", "cat")), ""));

                                1 Reply Last reply
                                0
                                • C Chris Maunder

                                  Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.

                                  cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                  C Offline
                                  C Offline
                                  Clumpco
                                  wrote on last edited by
                                  #131

                                  Here's a solution in APL V←'dog cat monkey dog horse dog' Q←'dog' V←(((V≠Q)⍳1)-⎕IO)↓V V←(⎕IO-(Q≠⌽V)⍳1)↓V Q←'cat' V←(((V≠Q)⍳1)-⎕IO)↓V V←(⎕IO-(Q≠⌽V)⍳1)↓V No doubt a true APL programmer could do it in one line.

                                  1 Reply Last reply
                                  0
                                  • C Chris Maunder

                                    Quote:

                                    There's probably a regex solution

                                    result = Regex.Replace("dog cat monkey dog horse dog", "^(dog|cat)*(.*?)((dog|cat)*)$", "$2",
                                    RegexOptions.IgnoreCase | RegexOptions.SingleLine);

                                    cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                    M Offline
                                    M Offline
                                    Marc Clifton
                                    wrote on last edited by
                                    #132

                                    Chris Maunder wrote:

                                    result = Regex.Replace

                                    That's sweet. And amazingly simple. Marc

                                    My Blog
                                    An Agile walk on the wild side with Relationship Oriented Programming

                                    1 Reply Last reply
                                    0
                                    • P Pete OHanlon

                                      Your former client base is showing mate - calling a method Stripper.

                                      Forgive your enemies - it messes with their heads

                                      "Mind bleach! Send me mind bleach!" - Nagy Vilmos

                                      My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                                      M Offline
                                      M Offline
                                      Marc Clifton
                                      wrote on last edited by
                                      #133

                                      Pete O'Hanlon wrote:

                                      Your former client base is showing mate - calling a method Stripper.

                                      I am scarred for life! ;P Marc

                                      My Blog
                                      An Agile walk on the wild side with Relationship Oriented Programming

                                      1 Reply Last reply
                                      0
                                      • H hairy_hats

                                        Quantum collapse occurs due to quantum interactions with something else ("observation"). There is no need for that interaction to be conscious or human, it just means that one quantum system is disturbed through interaction with something else - such as a cat. :)

                                        D Offline
                                        D Offline
                                        DariusLegion
                                        wrote on last edited by
                                        #134

                                        What the hell is the matter with you guys...? :sigh:

                                        1 Reply Last reply
                                        0
                                        • C Chris Maunder

                                          Won't work if you have "dog dog text". It will only remove the first "dog"

                                          cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                                          J Offline
                                          J Offline
                                          jsc42
                                          wrote on last edited by
                                          #135

                                          5th Jan: But you said there was nothing in the spec about whitespace, so only removing the first dog is permissible. FWIW: Here is my solution in JavaScript (not the fastest, but still quite short a) Only removing the first dog (if there are multiple dogs)

                                          alert(/^(dog|cat)*(.*?)(dog|cat)*$/.exec("dog cat monkey dog horse dog")[2])

                                          b) Allowing removal of packs of dogs and cats optionally separated by whitespace chars:

                                          alert(/^(\s*(dog|cat))*(.*?)((dog|cat)\s*)*$/.exec("dog cat monkey dog horse dog")[3])

                                          6th Jan: Modified Clarifications in other responses suggest that whitespace is to be preserved and is not significant when looking for leading / trailing texts and that a general solution is required rather than looking only for dogs and cats bracketing "dog cat monkey dog horse dog". So, today's JavaScript version is ...

                                          function strim(str, texts)
                                          {
                                          return str.replace(
                                          new RegExp(
                                          '^((\\s*)(' + // $2 = leading whitespace
                                          texts.join('|') +
                                          '))*(.*?)((' + // $4 = middle portion
                                          texts.join('|') +
                                          ')(\\s*)?)*$', // $7 = trailing whitespace
                                          'ig'
                                          ),
                                          '$2$4$7'
                                          );
                                          }

                                          alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]));
                                          alert(strim('dog dog text', [ 'dog', 'cat' ]));

                                          To see the spaces, change the alerts to

                                          alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~monkey~dog~horse~
                                          alert(strim('dog dog text', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~text

                                          Note: This will not work if the texts for testing at the start and end include any special RegExp chars, e.g.

                                          . * + ? {
                                          or }.

                                          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