Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


November 28, 2007

Function Finds the nth Occurrence of Substrings

This VBScript function comes in handy when working with paths
RSS
View this exclusive article with VIP access -- click here to join | See More Tips Articles Here | Reprints
Or sign up for our VIP Monthly Pass!

Download the Code Here

 Executive Summary:
Although VBScript offers the InStr and InStrRev functions to find the position of a substring, they only find the position of the substring's first occurrence. Sometimes, you might need to find the position of a different occurrence, such as the second or fourth occurrence of the substring. If you find yourself in this situation, you can use the nInStr function. This user-defined VBScript function lets you find the starting position of any occurrence of a substring.

Creating a function that finds the nth occurrence of a substring is one of those things I said I’d do someday but had never found the time to do. Because necessity is the mother of invention, "someday" actually arrived when I was recently confronted with a text file full of pathnames that pointed to files I needed to copy. I had to copy the files from a folder on one server to a folder with the same name on another server, then delete the original folder and its contents.

Writing code that copied the files and deleted the original folder was no big deal. However, extracting the folder names from the pathnames proved a little tricky. For example, suppose you need to extract folder names from pathnames that follow the format \\RemoteComputer\ShareName\FolderName. If you know the starting position of the fourth backslash (\), you can use VBScript's Right function to extract the folder name. The problem is that VBScript doesn't provide a function that lets you find the fourth occurrence of a substring. Its InStr and InStrRev functions only find the position of a substring's first occurrence. Thus, I created the nInStr function, which lets you find the starting position of any occurrence of a substring within another string.

The nInStr function's syntax is

nInStr(SourceString,
 SearchForString,WhichOccurrence)

where SourceString is the string being searched, SearchForString is the substring you're looking for, and WhichOccurrence is a number that specifies which occurrence of the substring you want (e.g., 1 for the first occurrence, 2 for the second occurrence, and so on). For example, if you want to know the starting position of the fourth backslash in \\DenverSrvr\Share1\Docs, you'd use

nInStr("\\DenverSrvr\Share1\Docs", _
"\",4)

If you want to use the nInStr function to help extract a folder's name from a pathname, the call to the function might look something like

SourceString = _
 "\\DenverSrvr\Share1\Docs"
ExtractFolderName = Right( _
 SourceString,Len(SourceString) _
 - nInStr(SourceString,"\",4))

Listing 1 shows the nInStr function. This function begins with the declaration of its name and three parameters. After that declaration, an initial value of 1 is assigned to a variable named StartPosition. This variable's value indicates where within the source string the function starts its search. A value of 1 means the function will start from the first character in the source string, a value of 2 means the function will start from the second character, and so on. Each time the function cycles through the For…Next statement at callout A in Listing 1, the StartPosition variable's value changes as long as the substring is found.

The key component in the For…Next loop is the code

FoundPosition = InStr(StartPosition, _
 strSource,strFind)

When the substring (strFind) is found within the source string (strSource), the starting position of the substring is stored in a variable named FoundPosition. The FoundPosition variable's value is then incremented by 1 and the resulting value is set to StartPosition, thereby creating a new starting position for the next iteration of the For…Next loop. This process continues until the substring isn't found or until the function has looped as many times as the occurrence variable dictates. When the nth occurrence of the substring is found, the starting position of that occurrence is assigned to FoundPosition; that position subsequently becomes the function's return value. When the nth occurrence of the substring isn't found, FoundPosition is set to zero, which becomes the function's return value.

You can download a .zip file that contains the code for the nInStr function by clicking the Download the Code Here button at the top of the page. This .zip file also contains a simple but somewhat entertaining HTML Application (HTA) that demonstrates the function's usage.

Share Your Scripting Experiences
Share your scripting discoveries, comments, solutions to problems, and experiences with products. Email your contributions to r2r@scriptingprovip.com. Please include your full name and phone number. We edit submissions for style, grammar, and length. If we print your submission, you'll get $100.

End of Article



Reader Comments

You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Managing Virtual Sprawl

As some wise person once said, nothing is ever truly free. Such is the case with VMs, which can quickly mutate from a cost-reducing Dr. Jekyll into a time-consuming, profligate nightmare that would do Mr. Hyde proud. ...

What service packs and fixes are available?

...


Related Articles Use the FileToArray Function to Read a Text File Into an Array

Use the GetToken Function to Parse Delimited Lines

A VBScript Version of VBA’s IIf Function

Handle Strings More Easily

Related Events Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Critical Challenges of ESI & Email Retention
Are you storing too much electronic information? Get expert legal advice and better understanding of what you are required to do as an IT professional.

Become a fan of Windows IT Pro on Facebook!
Join us on Facebook and be a fan of Windows IT Pro!

Sustainable Compliance: Are You Having a Resource Crisis?
Read this white paper to examine trends in compliance and security management and review approaches to reducing the cost and operational burden of compliance.

Rev Up Your IT Know-How with Our Recharged Magazine!
The improved Windows IT Pro provides trusted IT content with an enhanced new look and functionality! Get comprehensive coverage of industry topics, expert advice, and real-world solutions—PLUS access to over 10,000 articles online. Order today!

Get It All with Windows IT Pro VIP
Stock your IT toolbox with every solution ever printed in Windows IT Pro and SQL Server Magazine plus bonus Web-exclusive content on hot topics. Subscribe to receive the VIP CD and a subscription to your choice of Windows IT Pro or SQL Server Magazine!



Order Your Fundamentals CD Today!
Gain an introduction to Exchange, learn server security requirements, and understand how unified communications can play a role in your messaging strategies with this free Exchange CD.
Windows IT Pro Home Register About Us Affiliates / Licensing Media Kit Contact Us/Customer Service  
SQL Connected Home IT Library SuperSite FAQ Wininfo News
Europe Edition Office & SharePoint Pro Windows Dev Pro Windows Excavator 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing