用空格分割字符串的函数

学习提速专享!AI工具全家桶免费用 限时购周边加赠Coding Plan Lite,解锁20+主流AI工具,写代码、查资料快人一步! 阅读详情

Option Explicit
'===============================================
'Words.bas - string handling functions for words
'Author: Evan Sims         [esims@arcola-il.com]
'Based on a module by Kevin O'Brien
'Version - 1.2 (Sept. 1996 - Dec 1999)
'
'These functions deal with "words".
'Words = blank-delimited strings
'Blank = any combination of one or more spaces,
'        tabs, line feeds, or carriage returns.
'
'Examples:
'     pword("find 3 in here", 3)     = "in"      3rd word
'     words("find 3 in here")        = 4         number of words
'     split("here's /s more", "/s")  = "more"    Returns words after split identifier (/s)
'   delWord("find 3 in here", 1, 2)  = "in here" delete 2 words, start at 1
'   midWord("find 3 in here", 1, 2)  = "find 3"  return 2 words, start at 1
'   wordPos("find 3 in here", "in")  = 3         word-number of "in"
' wordCount("find 3 in here", "in")  = 1         occurrences of word "in"
' wordIndex("find 3 in here", "in")  = 8         position of "in"
' wordIndex("find 3 in here", 3)     = 8         position of 3rd word
' wordIndex("find 3 in here", "3")   = 6         position of "3"
'wordLength("find 3 in here", 3)     = 2         length of 3rd word
'
'Difference between Instr() and wordIndex():
'     InStr("find 3 in here", "in")   = 2
' wordIndex("find 3 in here", "in")   = 8
'
'     InStr("find 3 in here", "her")  = 11
' wordIndex("find 3 in here", "her")  = 0
'===============================================

Public Function Pword(ByVal sSource As String, _
                                 n As Long) As String
'=================================================
' Word retrieves the nth word from sSource
' Usage:
'    Word("red blue green ", 2)   "blue"
'=================================================
Const SP    As String = " "
Dim pointer As Long   'start parameter of Instr()
Dim pos     As Long   'position of target in InStr()
Dim x       As Long   'word count
Dim lEnd    As Long   'position of trailing word delimiter

sSource = CSpace(sSource)

'find the nth word
x = 1
pointer = 1

Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
   If x = n Then                               'the target word-number
      lEnd = InStr(pointer, sSource, SP)       'pos of space at end of word
      If lEnd = 0 Then lEnd = Len(sSource) + 1 '   or if its the last word
      Pword = Mid$(sSource, pointer, lEnd - pointer)
      Exit Do                                  'word found, done
   End If
 
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'word not found
   x = x + 1                                   'increment word counter
 
   pointer = pos + 1                           'start of next word
Loop
 
End Function

Public Function Words(ByVal sSource As String) As Long
'=================================================
' Words returns the number of words in a string
' Usage:
'    Words("red blue green")   3
'=================================================
Const SP    As String = " "
Dim lSource As Long    'length of sSource
Dim pointer As Long    'start parameter of Instr()
Dim pos     As Long    'position of target in InStr()
Dim x       As Long    'word count

sSource = CSpace(sSource)
lSource = Len(sSource)
If lSource = 0 Then Exit Function

'count words
x = 1
pointer = 1

Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'no more words
   x = x + 1                                   'increment word counter
 
   pointer = pos + 1                           'start of next word
Loop
If Mid$(sSource, lSource, 1) = SP Then x = x - 1 'adjust if trailing space
Words = x
End Function

Public Function WordCount(ByVal sSource As String, _
                                sTarget As String) As Long
'=====================================================
' WordCount returns the number of times that
' word, sTarget, is found in sSource.
' Usage:
'    WordCount("a rose is a rose", "rose")     2
'=================================================
Const SP    As String = " "
Dim pointer As Long    'start parameter of Instr()
Dim lSource As Long    'length of sSource
Dim lTarget As Long    'length of sTarget
Dim pos     As Long    'position of target in InStr()
Dim x       As Long    'word count

lTarget = Len(sTarget)
lSource = Len(sSource)
sSource = CSpace(sSource)


'find target word
pointer = 1
Do While Mid$(sSource, pointer, 1) = SP       'skip consecutive spaces
   pointer = pointer + 1
Loop
If pointer > lSource Then Exit Function       'sSource contains no words

Do                                            'find position of sTarget
   pos = InStr(pointer, sSource, sTarget)
   If pos = 0 Then Exit Do                    'string not found
   If Mid$(sSource, pos + lTarget, 1) = SP _
   Or pos + lTarget > lSource Then            'must be a word
      If pos = 1 Then
         x = x + 1                            'word found
      ElseIf Mid$(sSource, pos - 1, 1) = SP Then
         x = x + 1                            'word found
      End If
   End If
   pointer = pos + lTarget
Loop
WordCount = x

End Function

Public Function WordPos(ByVal sSource As String, _
                              sTarget As String) As Long
'=====================================================
' WordPos returns the word number of the
' word, sTarget, in sSource.
' Usage:
'    WordPos("red blue green", "blue")    2
'=================================================
Const SP       As String = " "
Dim pointer    As Long    'start parameter of Instr()
Dim lSource    As Long    'length of sSource
Dim lTarget    As Long    'length of sTarget
Dim lPosTarget As Long    'position of target-word
Dim pos        As Long    'position of target in InStr()
Dim x          As Long    'word count

lTarget = Len(sTarget)
lSource = Len(sSource)
sSource = CSpace(sSource)


'find target word
pointer = 1
Do While Mid$(sSource, pointer, 1) = SP       'skip consecutive spaces
   pointer = pointer + 1
Loop
If pointer > lSource Then Exit Function       'sSource contains no words

Do                                            'find position of sTarget
   pos = InStr(pointer, sSource, sTarget)
   If pos = 0 Then Exit Function              'string not found
   If Mid$(sSource, pos + lTarget, 1) = SP _
   Or pos + lTarget > lSource Then            'must be a word
      If pos = 1 Then Exit Do                 'word found
      If Mid$(sSource, pos - 1, 1) = SP Then Exit Do
   End If
   pointer = pos + lTarget
Loop


'count words until position of sTarget
lPosTarget = pos                             'save position of sTarget
pointer = 1
x = 1
Do
   Do While Mid$(sSource, pointer, 1) = SP   'skip consecutive spaces
      pointer = pointer + 1
   Loop
   If pointer >= lPosTarget Then Exit Do     'all words have been counted
   pos = InStr(pointer, sSource, SP)         'find next space
   If pos = 0 Then Exit Do                   'no more words
   x = x + 1                                 'increment word count
   pointer = pos + 1                         'start of next word
Loop
WordPos = x
End Function

Public Function WordIndex(ByVal sSource As String, _
                                vTarget As Variant) As Long
'===========================================================
' WordIndex returns the byte position of vTarget in sSource.
' vTarget can be a word-number or a string.
' Usage:
'   WordIndex("two plus 2 is four", 2)       5
'   WordIndex("two plus 2 is four", "2")    10
'   WordIndex("two plus 2 is four", "two")   1
'===========================================================
Const SP    As String = " "
Dim sTarget As String  'vTarget converted to String
Dim lTarget As Long    'vTarget converted to Long, or length of sTarget
Dim lSource As Long    'length of sSource
Dim pointer As Long    'start parameter of InStr()
Dim pos     As Long    'position of target in InStr()
Dim x       As Long    'word counter

lSource = Len(sSource)
sSource = CSpace(sSource)

If VarType(vTarget) = vbString Then GoTo strIndex
If Not IsNumeric(vTarget) Then Exit Function
lTarget = CLng(vTarget)                       'convert to Long

'find byte position of lTarget (word number)
x = 1
pointer = 1


Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
  
   If x = lTarget Then                         'word-number of Target
      If pointer > lSource Then Exit Do        'beyond end of sSource
      WordIndex = pointer                      'position of word
      Exit Do                                  'word found, done
   End If
 
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'word not found
   x = x + 1                                   'increment word counter
   pointer = pos + 1
Loop

Exit Function
strIndex:
sTarget = CStr(vTarget)
lTarget = Len(sTarget)
If lTarget = 0 Then Exit Function              'nothing to count

'find byte position of sTarget (string)
pointer = 1
Do
   pos = InStr(pointer, sSource, sTarget)
   If pos = 0 Then Exit Do
   If Mid$(sSource, pos + lTarget, 1) = SP _
   Or pos + lTarget > lSource Then
      If pos = 1 Then Exit Do
      If Mid$(sSource, pos - 1, 1) = SP Then Exit Do
   End If
   pointer = pos + lTarget
Loop

WordIndex = pos

End Function

Public Function WordLength(ByVal sSource As String, _
                                       n As Long) As Long
'=========================================================
' Wordlength returns the length of the nth word in sSource
' Usage:
'    WordLength("red blue green", 2)    4
'=========================================================
Const SP    As String = " "
Dim lSource As Long   'length of sSource
Dim pointer As Long   'start parameter Instr()
Dim pos     As Long   'position of target with InStr()
Dim x       As Long   'word count
Dim lEnd    As Long   'position of trailing word delimiter

sSource = CSpace(sSource)
lSource = Len(sSource)

'find the nth word
x = 1
pointer = 1

Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
   If x = n Then                               'the target word-number
      lEnd = InStr(pointer, sSource, SP)       'pos of space at end of word
      If lEnd = 0 Then lEnd = lSource + 1      '   or if its the last word
      WordLength = lEnd - pointer
      Exit Do                                  'word found, done
   End If
 
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'word not found
   x = x + 1                                   'increment word counter
 
   pointer = pos + 1                           'start of next word
Loop

End Function

Public Function DelWord(ByVal sSource As String, _
                                    n As Long, _
                      Optional vWords As Variant) As String
'===========================================================
' DelWord deletes from sSource, starting with the
' nth word for a length of vWords words.
' If vWords is omitted, all words from the nth word on are
' deleted.
' Usage:
'   DelWord("now is not the time", 3)     "now is"
'   DelWord("now is not the time", 3, 1)  "now is the time"
'===========================================================
Const SP    As String = " "
Dim lWords  As Long    'length of sTarget
Dim lSource As Long    'length of sSource
Dim pointer As Long    'start parameter of InStr()
Dim pos     As Long    'position of target in InStr()
Dim x       As Long    'word counter
Dim lStart  As Long    'position of word n
Dim lEnd    As Long    'position of space after last word

lSource = Len(sSource)
DelWord = sSource
sSource = CSpace(sSource)
If IsMissing(vWords) Then
   lWords = -1
ElseIf IsNumeric(vWords) Then
   lWords = CLng(vWords)
Else
   Exit Function
End If

If n = 0 Or lWords = 0 Then Exit Function      'nothing to delete

'find position of n
x = 1
pointer = 1

Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
   If x = n Then                               'the target word-number
      lStart = pointer
      If lWords < 0 Then Exit Do
   End If
  
   If lWords > 0 Then                          'lWords was provided
      If x = n + lWords - 1 Then               'find pos of last word
         lEnd = InStr(pointer, sSource, SP)    'pos of space at end of word
         Exit Do                               'word found, done
      End If
   End If
  
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'word not found
   x = x + 1                                   'increment word counter
 
   pointer = pos + 1                           'start of next word
Loop
If lStart = 0 Then Exit Function
If lEnd = 0 Then
   DelWord = Trim$(Left$(sSource, lStart - 1))
Else
   DelWord = Trim$(Left$(sSource, lStart - 1) & Mid$(sSource, lEnd + 1))
End If
End Function

Public Function MidWord(ByVal sSource As String, _
                                    n As Long, _
                      Optional vWords As Variant) As String
'===========================================================
' MidWord returns a substring sSource, starting with the
' nth word for a length of vWords words.
' If vWords is omitted, all words from the nth word on are
' returned.
' Usage:
'   MidWord("now is not the time", 3)     "not the time"
'   MidWord("now is not the time", 3, 2)  "not the"
'===========================================================
Const SP    As String = " "
Dim lWords  As Long    'vWords converted to long
Dim lSource As Long    'length of sSource
Dim pointer As Long    'start parameter of InStr()
Dim pos     As Long    'position of target in InStr()
Dim x       As Long    'word counter
Dim lStart  As Long    'position of word n
Dim lEnd    As Long    'position of space after last word

lSource = Len(sSource)
sSource = CSpace(sSource)
If IsMissing(vWords) Then
   lWords = -1
ElseIf IsNumeric(vWords) Then
   lWords = CLng(vWords)
Else
   Exit Function
End If

If n = 0 Or lWords = 0 Then Exit Function              'nothing to delete

'find position of n
x = 1
pointer = 1

Do
   Do While Mid$(sSource, pointer, 1) = SP     'skip consecutive spaces
      pointer = pointer + 1
   Loop
   If x = n Then                               'the target word-number
      lStart = pointer
      If lWords < 0 Then Exit Do               'include rest of sSource
   End If
  
   If lWords > 0 Then                          'lWords was provided
      If x = n + lWords - 1 Then               'find pos of last word
         lEnd = InStr(pointer, sSource, SP)    'pos of space at end of word
         Exit Do                               'word found, done
      End If
   End If
  
   pos = InStr(pointer, sSource, SP)           'find next space
   If pos = 0 Then Exit Do                     'word not found
   x = x + 1                                   'increment word counter
 
   pointer = pos + 1                           'start of next word
Loop
If lStart = 0 Then Exit Function
If lEnd = 0 Then
   MidWord = Trim$(Mid$(sSource, lStart))
Else
   MidWord = Trim$(Mid$(sSource, lStart, lEnd - lStart))
End If
End Function

Public Function CSpace(sSource As String) As String
'==================================================
'CSpace converts blank characters
'(ascii: 9,10,13,160) to space (32)
'
'  cSpace("a" & vbTab   & "b")  "a b"
'  cSpace("a" & vbCrlf  & "b")  "a  b"
'==================================================
Dim pointer   As Long
Dim pos       As Long
Dim x         As Long
Dim iSpace(3) As Integer

' define blank characters
iSpace(0) = 9    'Horizontal Tab
iSpace(1) = 10   'Line Feed
iSpace(2) = 13   'Carriage Return
iSpace(3) = 160  'Hard Space

CSpace = sSource
For x = 0 To UBound(iSpace) ' replace all blank characters with space
   pointer = 1
   Do
      pos = InStr(pointer, CSpace, Chr$(iSpace(x)))
      If pos = 0 Then Exit Do
      Mid$(CSpace, pos, 1) = " "
      pointer = pos + 1
   Loop
Next x

End Function

Public Function SplitString(iSource As String, iTarget As String, Optional BeforeTarget As Boolean = False) As String
'==================================================
'Returns the characters before or after the split
'identifier. By default will return text after id,
'set BeforeTarget as true to return the text before
'it.
'==================================================
If BeforeTarget = True Then
   SplitString = DelWord(iSource, WordPos(iSource, iTarget))
Else
   SplitString = DelWord(iSource, 1, WordPos(iSource, iTarget))
End If

End Function

QTP-14 VBScript VBS基础 QTP-14 VBScript VBS基础 1.     熟练掌握下面的方法: Strings: Lcase() & Ucase()      ‘大小写 strComp()         StrReverse()          ‘倒序 Len() Left() Right() Mid() InStr() InStrRev 阅读详情

相关推荐

谨慎使用IsMissing函数

在VB6中提供了一个很好用的函数IsMissing,可以用来判断用户是否对缺省参数赋值,比如有以下一个函数体: Public Property Get Item(Optional ByRef Index As Integer, Optional ByRef Name As String) As TDMAttachment Dim i As Long Dim

lyserver的专栏 4568

VB中判断空的几种方法,Null, Missing, Empty, Nothing, vbNullString区别

  vb6中存在几个虚幻的值:Null、Missing、Empty、Nothing、vbNullString。除了最后一个之外,每一个值都不能直接用“a=值”来判断。下面分别解释一下这几个值的含义。 1、Null Null指一个不合法的数据,判断一个变量是否为Null使用isNull函数。 这种数据通常出现在三种情况下: (1)最简单的,函数直接返回Null给调用方。譬如 Function ...

devops 1万+

vb6的一些自己写的函数 用于类型转换,十六进制输出,字节转换

基本的函数 '用于将 一个变量 的类型打印出来。 Public Function getVarTypeToString(ByVal m_value As VbVarType) As String 'varType typename 'information: IsArray IsDate IsEmpty IsError IsMissing IsNULL isNumric IsO...

weixin_34357887的博客 445

c语言字符串分割函数mysplit,可处理多个空格

以参数ch字符分割分割char数组到char二维数组中,返回词的个数 可处理多个重复ch的情况,无论开头,中间,还是结尾int mysplit(char *pstr, char(*pcutcmd)[10], char ch) { int ret = 0; if (NULL != pstr && NULL != pcutcmd) { char *t

qq_28203631的博客 2001

C#根据空格分割字符串Split函数可以是多个空格

<br />string[]strArray=yourString.Split(newchar[]{''});publicstaticvoidMain(){stringstrS="CSDNC#论坛版竹...";string[]args=strS.Split('');ArrayListarr=newArrayList();for(inti=0;i <br />string[]   strArray   =   yourString.Split(   new   char[]   {'   '}   );<b

1万+

【C++基础】strtok()函数的用法(能去除冗余空格!!有关于被分割字符串的分析!!)

文章目录1.函数原型2.函数功能3.举例演示 1.函数原型 char *strtok(char *s,const char *delim) 2.函数功能 1.分解字符串为一组字符串,s为要分解的字符串,delim为分隔字符串 2.strtok()用来将字符串分割成一个个片段,参数s指向将要被分隔的字符串,参数delim则为分隔字符串,当strtok()在参数s的字符串中发现到参数delim的分隔字符时,则会将该字符改为’\0’字符,在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数

AloneYueCSDN 2387

c语言将字符串空格分割_C语言对字符串分割操作函数函数sscanf()的用法...

sscanf() - 从一个字符串中读进与指定格式相符的数据.函数原型:int sscanf( string str, string fmt, mixed var1, mixed var2 ...);int scanf( const char *format [,argument]... );说明:sscanf与scanf类似,都是用于输入的,只是后者以屏幕(stdin)为输入源,前者以固定字符串...

weixin_39620065的博客 2122

C++搞个split函数,把字符串空格分割

直接copy这个函数就行: #include<iostream> using namespace std; #include<string> #include <regex> //按空格分隔,返回vector<std::string>类型。有时间想想怎么把这个函数搞成我所有程序都能引入头文件直接用的。 vector<string> split(string text) { regex ws_re("\\s+"); // 这个可以把所有空格

FreshHhand的博客 2172

c语言将字符串空格分割_如何在c++中实现字符串分割函数split详解

前言在学习c++中string相关基本用法的时候,发现了sstream的istringstream[1]可以将字符串类似于控制台的方式进行输入,而实质上这个行为等同于利用空格将一个字符串进行了分割,于是考虑到可以利用这个特性来实现c++库函数中没有的字符串分割函数splitstring src("Avatar 123 5.2 Titanic K");istringstream istrStream...

weixin_33901087的博客 6456

java split()函数字符串分割(通过空格)!

给定一个带n个空格的长字符串,我们要根据空格把他们分割开来,例如:  String str="  this is a txt  !  "; 首先我们要对收尾两端的空格进行处理,String类中的trim()函数,可以解决这个问题,会把字符串的首尾空格去除掉,并返回处理后的字符串String str1=str.trim(); 此时str1="this is a txt !";

Star_CSU的博客 3618

保留空格字符串分割函数

当我用StringTokenizer类去分割字符串的时候,出现了一个问题,就是我想在字符串里保留的空格没有了。所以我不得不自己写了一个字符串分割函数如下        import Java.util.*; public class Split {         public String[] split(String str,char x)         {

fengyee_zju的专栏 1031

2022-02-24 Java中的 split 函数是用于按指定字符(串)或正则去分割某个字符串,从字符串中 以单个或多个空格进行分隔 提取字符串

一、split函数,regex -- 正则表达式分隔符。limit -- 分割的份数。 public String[] split(String regex, int limit) 二、测试代码 1、java代码 public class Main { public static void main(String[] args) { System.out.println("Hello World"); String str = ...

海月汐辰 762

精简代码:Python的split方法函数可以分割字符串成列表,默认是以空格作为分隔符sep来分割字符串

Python的split方法函数可以分割字符串成列表,默认是以空格作为分隔符sep来分割字符串。 [python] view plaincopy In [1]: s = "www jeapedu com"      In [2]: print s.split()   ['www', 'jeapedu', 'com']  

cnmCSDN456的专栏 3万+

c语言以空格分割字符串_C语言: 利用sscanf() 函数分割字符串

头文件:#include sscanf()函数用于从字符串中读取指定格式的数据,其原型如下:int sscanf (char *str, char * format [, argument, ...]);【参数】参数str为要读取数据的字符串;format为用户指定的格式;argument为变量,用来保存读取到的数据。【返回值】成功则返回参数数目,失败则返回-1,错误原因存于errno 中。ssc...

weixin_39756895的博客 3301

C++实现按指定子串分割母串(split)函数空格分割string字符串

C++没有自带的split函数,需要我们自己写一个 vector<string> split(const string& str, const string& delim) { vector<string> res; if("" == str) return res; //先将要切割的字符串string类型转换为char*类型 char * strs = new char[str.length() + 1] ; //不要忘了 strcp

weixin_47826078的博客 563

Lua实现字符串分割函数(一个含空格,一个不含空格)

Lua函数实现方式

『18年码龄、20多年的IT经验』 976

VBA分割字符串字符串多个位置有不确定个数的空格

使用VBA分割多个空格

weixin_46610533的博客 927
上一篇: ADSL上网中的几则困惑
下一篇: 如何用VB开发游戏外挂
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金蝶高级实施顾问

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值