xici胡同logo职场
职场首页|论坛排行|新建论坛|频道导航
当前位置:胡同口 > 职场 > 搜索引擎优化讨论版 > 看贴 收藏  

用InStr函数实现代码减肥

返回[搜索引擎优化讨论版]  关闭窗口 | 隐藏边栏
 
christinazt 发表于:07-12-20 20:57 [显示全部帖子]
可以采用“旁门左道”的方式使用Instr函数实现代码的简练。下面是一个典型的例子,检测字符串中是否包含一个元音字母:

1、普通的方法:


If UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$(char) = "O" Or UCase$(char) = "U" Then

' it is a vowel

End If


2、更加简练的方法:

If InStr("AaEeIiOoUu", char) Then

' it is a vowel

End If

同样,通过单词中没有的字符作为分界符,使用InStr来检查变量的内容。下面的例子检查Word中是否包含一个季节的名字: 1、普通的方法:

If LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _ "summer" Or LCase$(word) = "fall" Then

' it is a season's name

End If


2、更加简练的方法:

If Instr(";winter;spring;summer;fall;", ";" & word & ";") Then

' it is a season's name

End If

有时候,甚至可以使用InStr来替代Select

Case代码段,但一定要注意参数中的字符数目。下面的例子中,转换数字0到9的相应英文名称为阿拉伯数字: 1、普通的方法:


Select Case LCase$(word)

Case "zero"

result = 0

Case "one"

result = 1

Case "two"

result = 2

Case "three"

result = 3

Case "four"

result = 4

Case "five"

result = 5

Case "six"

result = 6

Case "seven"

result = 7

Case "eight"

result = 8

Case "nine"

result = 9

End Select

2、更加简练的方法:

result = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", ";" & LCase$(word) & ";") \ 6
 
00
返回[搜索引擎优化讨论版]  关闭窗口 | 隐藏边栏
本地热帖
[全国漫游] 更多>>
西祠智投

对不起,匆匆过客不能发帖或者跟帖:(

请先登录或者注册

本版精品更多>>

相关热贴

没有其他相关标签