acantor Posted January 14, 2011 Report Share Posted January 14, 2011 In MEP, is there a direct way -- or even an hack! -- to count the number of times that a specific string appears in a text variable? In pseudo-code: %Text% = "Abc 123 def 345 A" Count("A" in %Text%) = 2 Count(" " in %Text%) = 4 Count("Abc" in %Text%) = 1 Count ("Hello" in %Text%) = 0 Or am I stuck with having to "manually" parse the text variable? Quote Link to comment Share on other sites More sharing options...
Cory Posted January 14, 2011 Report Share Posted January 14, 2011 Copy the variable to a temp var. Get the length of the var. Get the length of the search string. Variable Modify String Replace Substring on the temp and include the option for all instances. Now get the length again. Subtract this length from the beginning length and divide by the search string length. Voila! Quote Link to comment Share on other sites More sharing options...
kevin Posted January 14, 2011 Report Share Posted January 14, 2011 There is no direct way that I am aware of. This sample macro will do it. // Initialization Variable Set String %SearchFor% to "Hello" // Enter the string to search for Variable Set Bool %Done% to "False" // Initialize Done flag Variable Modify String %sTemp%: Copy Whole Text (%Text%) // Make a copy of your original string Variable Set Integer %Count% to 0 // Count the instances of %SearchFor% in %sTemp% Repeat Until %Done% Equals "True" Variable Modify String: Replace "Hello" in %sTemp% with "" // Do not check the 'Replace All Instances' box Variable Modify Integer %Count%: Increment // See if we're done If Variable %sTemp% Contains "Hello" Variable Set Bool %Done% to "True" End If End Repeat I am curious if someone else has an easier/shorter/faster way. Quote Link to comment Share on other sites More sharing options...
kevin Posted January 14, 2011 Report Share Posted January 14, 2011 Copy the variable to a temp var. Get the length of the var. Get the length of the search string. Variable Modify String Replace Substring on the temp and include the option for all instances. Now get the length again. Subtract this length from the beginning length and divide by the search string length. Voila! Cool hack Cory. You posted this while I was composing my (longer) solution. Quote Link to comment Share on other sites More sharing options...
acantor Posted January 14, 2011 Author Report Share Posted January 14, 2011 OK, so there is no direct way to count the number of instances of y within x. Oh, well... My solution is almost identical to Cory's, although his is more versatile. (For my purpose, the string to count is only one character long, so I do not need the division step.) Thanks to both of you! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.