matching strings

For questions regarding programming in the EViews programming language.

Moderators: EViews Gareth, EViews Moderator, EViews Jason, EViews Matt

tchaithonov
Posts: 168
Joined: Mon Apr 13, 2009 7:39 am
Location: New York City

matching strings

Postby tchaithonov » Wed Feb 16, 2011 10:30 am

Hey Guys, how are you?

I have this string with non-unique elements in it, and I need to find out the positions of a particular element:
e.g.,

Code: Select all

%names = "John Paul Andrew John John Tom"
Let's say I want to find out the positions of all the "John" in this string. I know with @wfind you can find out the position of the first one (in this case, 1), but is there an easy way where Eviews can tell me the answer "1 4 5" in one shot? I have thought about putting %names into a svec but then I feel that it's a bit cumbersome. If I do @instr(%name, "John"), it only gives me the position of where the first "John" starts. Would you please let me know your thoughts on this? Thanks.

Tchaithonov

EViews Glenn
EViews Developer
Posts: 2682
Joined: Wed Oct 15, 2008 9:17 am

Re: matching strings

Postby EViews Glenn » Wed Feb 16, 2011 12:16 pm

I can't think of an easy way since the word seeking functions only search for a single instance. Here's a bit of a hack which calls the word seeking function recursively, lopping off parts of a copy of the string as it goes. It returns the result in the form of a string of elements. If you want it as a numeric vector we can make a quick change to the subroutine. Let me know. Note also that I do the comparison as a case-sensitive @wfind. You can change this to a non-case sensitive @wfindc if you wish.

I've run a couple of quick tests and it looks okay, but you should do a bit of shakeout before using it for anything serious.

Here's the subroutine...

Code: Select all

subroutine local wfindall(string result, string src, string target) string srctemp = src result = "" ' initialize ' initialize recursion !found = 0 !posit= 0 !try = @wfind(srctemp, target) ' get the first match ' recursive loop while (!try <> 0) !found = !found + 1 result = result + " " + @str(!try + !posit) ' accumulate the result srctemp = @wmid(srctemp, !try+1) ' get the remainder string !posit= !posit + !try ' increment the number of trimmed !try = @wfind(srctemp, target) ' look for the next wend result = @trim(result) ' cleanup endsub
and an example of calling it

Code: Select all

string result call wfindall(result, %names, "John")
As I said, if you want this as a numeric vector, it's a quick modification.

tchaithonov
Posts: 168
Joined: Mon Apr 13, 2009 7:39 am
Location: New York City

Re: matching strings

Postby tchaithonov » Wed Feb 16, 2011 1:44 pm

Hi Glenn,

That's great. I think it serves the purpose I am looking for. Thanks.

Tchaithonov


Return to “Programming”

Who is online

Users browsing this forum: No registered users and 2 guests