The Many Uses of the Split Function

The Many Uses of the Split Function

s Visual Basic and VBScript have progressed from version to version, chances are you have not kept up to date with some of the new functions introduced in the later releases. I have met many developers who are unaware of the existence of some really useful functions in VB6 or in VBScript that could help in coding VB or ASP applications. These developers rely on older workarounds for writing code that could be handled by the new built-in functions. In this installment of Tactical ASP, I explore the new explore the new “Split” function and its myriad uses.

The Split function may not necessarily be new to you and you probably already looked at it and said, “Ho hum. Another functionwho needs it!” But waitdon’t drop this function into the trash yet. The Split function can provide unexpected returns if used properly.

What’s the Split?
Let’s look at the function itself. The Split function, according to the documentation, “returns a zero based, one-dimensional array containing a specified number of substrings.” Yes, I can hear the groans; “oh no, not another array function. I don’t use no stinkin’ arrays in my code anyway!”

Don’t give up yet. There is hope. The Split function is defined by this syntax:

Split(expression [, delimiter [, count [, compare]]])

This is how it is explained:

  • The function name is Split, and yes, it is a function, so it needs to be on the right hand side of an equal-to sign.
  • “Expression” is a required string expression containing substrings and delimiters.
  • “Delimiter” is an optional string identifying the delimiter character. By default, a space character (” “) is considered to be the delimiter.
  • “Count” is an optional number of substrings to return. The default is -1, which indicates all substrings are to be returned.
  • “Compare” is an optional numeric value signifying how the comparison should take place for evaluating substrings. A 0 indicates binary comparison; a 1 (the default) signifies textual comparison.

Given a text string, the Split function can quickly and efficiently break it down into an array of strings, based on your chosen delimiter. So, if you had the following string:

“This is the tactical ASP column by Rama Ramachandran”

the following code breaks the string into an array of strings, each containing one word.

Dim strAryWordsDim strValuestrValue = “This is the tactical ASP column by Rama Ramachandran”strAryWords = Split(strValue, ” “)’ – strAryWords is now an array Dim iFor i = 0 to Ubound(strAryWords)	Response.Write i & ” = ” & strAryWords(i) & “
“Next

The above code will produce the following output:

0 = This1 = is2 = the3 = tactical4 = ASP5 = column6 = by7 = Rama8 = Ramachandran

So, What’s the Big Deal with the Split Function?
You can use the Split function to quickly parse a text string and break it into an array. Working with an array is easier if you need to access a particular value quickly or iterate through all values. You can therefore replace all the following code, with the one line Split function we used above.

Dim strValueDim strAryWords()Dim i, iCountstrValue = “This is the tactical ASP column by Rama Ramachandran”i = Instr(strValue, ” “)iCount = 0Do While i > 0	Redim Preserve strAryWords(iCount)	strAryWords(iCount) = Left(strValue, i-1)	iCount = iCount + 1	strValue = Mid(strValue, i+1)	i = Instr(strValue, ” “)LoopIf strValue <> “” Then	Redim Preserve strAryWords(iCount)	strAryWords(iCount) = strValueEnd if’ – NOW, strAryWords is an array of all the words in the sentence.’ – All the above code can be replaced by one function callstrAryWords = Split(strValue, ” “)

You can see how the built-in function can be faster and more efficient than a lot of interpreted code, especially in an ASP application.

What the documentation does not indicate is that the Split function does not just use a single character as a delimiter?this is where its myriad uses pop up. You can use any text string as a delimiter with the Split function. Let us see how we can use this.

Suck in an Entire File from Disk into a Memory Array
There is one use of the Split function that I bet most of you did not think of or know about. The Split function can be used to suck in an entire file from disk into a neat memory array in one fell swoop. Let’s see how we used to do it and see how we can do it now.

This is the old way (pseudocode):
Open a File
Read one Line
Place the line into the memory array as an item
Read the next line
Till we are at end of the file
Close the file


This is the new way (pseudocode):
Open the file
Read entire file into a text string in memory
Close the file
Split entire file into its separate lines, placing each line into memory array as an item?using the Split function

And here’s the code for a Visual Basic application:

Dim iFile as integerDim strFileBuff as stringDim strAryLines() as string’ – Get a handle for the fileiFile = FreeFile’ – Open the fileOpen “C:FileName.txt” for input as #iFile’ – Read entire file into a text string in memorystrFileBuff = Input(LOF(iFile), #iFile)’ – close the fileClose #iFile’ – split entire file, placing each line into array as an itemstrAryLines = Split(strFileBuff, vbCrLF)

The magic happens at the very last line. Before that, we have sucked an entire file from disk into a memory variable using the single line of code:

strFileBuff = Input(LOF(iFile), #iFile)

This code reads an entire line into a memory variable (I tested this with a 25MB text file containing 25 million characters separated into 118,000 lines on a machine with 128MB RAM, running Win2000 Professional with no problems?it read the file in under two seconds). After closing the file, the Split function uses the end-of-line characters (Carriage return and Line Feed, or vbCrLF) to split the memory variable into an array of lines from the file in memory?again, in under two seconds. At the end of the above code, you have every line from the file in your memory array that you can then manipulate. You can find the total number of lines in the file by using the UBound function on the Array variable, and you can access any line by using the Array Name (item number) notation.

To use the code in an ASP page, you use the FileSystemObject to read a text file and use the ReadAll method to read the entire contents of the file into a variable. Then use the function to split it into an array.

Count the Number of Times a Word Occurs
You can use the same split function to also count the number of times a word occurs in a file. Using the same code as above, we can read the file into a memory text variable. Instead of using the vbCrLF characters to split the variable into an array, use the word you are counting for. For example, to find out the number of times the word “cool” appears in a text file, use this code:

‘ – split entire file, placing each line into array as an itemstrAryLines = Split(strFileBuff, “cool”)

Then you can find out the number by using this line of code:

intCount = Ubound(strAryLines)

You can also use the same technique to count the number of times a word occurs within the content of a record. Just substitute the file contents with your record contents. Assuming you had opened a recordset called objRS, you could use the following code:

‘ – split entire file, placing each line into array as an itemstrAryLines = Split(objRS(“FieldName”), “cool”)intCount = Ubound(strAryLines)

Rank Your Records
If you are using Access as your back-end database, you can use the Split function within an Access query to return records that contain the words “cool” ranked in order based on the number of times the word “cool” occurs within the text. To do so, use the following code to create a generic function that returns a count of the number of times a word occurs within another text string (your field). As you can see, this function uses the split function to break the text apart at the word and returns the count:

Function GetCount(ByVal strText, ByVal strWord)    GetCount = UBound(Split(strText, strWord))End Function

Then use the GetCount function within your query to bring back ranked records. Use the following SQL as your query. The reason why it will work in Access is that Access supports the UBound and the Split function. If you try this query within any other database, such as SQL Server, you will not be able to use the Split and UBound functions within the query itself.

SELECT Table1.Field1, Table1.Field2…FROM Table1WHERE Table1.Field1 LIKE “*cool*”ORDER BY GetCount(Table1.Field1, “cool”) DESC;

devx-admin

devx-admin

Share the Post:
AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s