Jump to content
Macro Express Forums

Number of strings contained in a text variable


Recommended Posts

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?

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...