取右起-前字符串的问题

湖中仙人 2008-12-06 04:37:05
如下面的类型的字符串,我想得到结果类型的字符串怎么做;我想取从右边起的第一个-前的字符串??
原字符串:asdf152-s-01 结果:asdf152-s
原字符串:asdf152-01 结果:asdf152
...全文
199 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
girlhappy 2008-12-08
  • 打赏
  • 举报
回复
Dim str As String = "asdf152-s-01 "
Dim a As String() = str.replace("-01","")
MsgBox(a)
直接這樣不就可以了
下面那个字符串同上
dreamice01 2008-12-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 bw555 的回复:]
VB.NET code Dim str As String = "asdfasdfa-sdf"
Dim a As String() = str.Split("-")
MsgBox(Mid(str, 1, Len(str) - Len(a(a.Length - 1)) - 1))
[/Quote]

这个用法我最喜欢,呵呵
yanlongwuhui 2008-12-08
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 yanlongwuhui 的回复:]
字符串中不一定有“-”时,参考如下:
Dim strTemp As String
Dim intPos As Integer
strTemp = "asdf152-s-01"
intPos = strTemp.LastIndexOf("-")
If intPos < 0 Then
Else
strTemp = strTemp.Substring(0, strTemp.LastIndexOf("-"))
End If
[/Quote]

LastIndexOf是最后一个匹配项的索引位置,因为从0开始,位置直接做长度就可以了(因为索引值是从0开始的,索引位置加1就是截取到含匹配项的字符串的长度,再减去1就是前面字符的长度)
小猪飞飞 2008-12-08
  • 打赏
  • 举报
回复
老实说,Lastindex比较明白,不错,顺便说下9楼,回去再动下脑筋去.要是Dim str As String = "asdf152-01 -s-01 " ,那不搞笑了/
sjxwb 2008-12-07
  • 打赏
  • 举报
回复
'参数说明:strSource为一行的内容;strStartFind为间隔前的字符串;strEndFind为间隔后的字符串
'返回的字符串就是中间的值
Public Function SubStr(ByVal strSource As String, ByVal strStartFind As String, ByVal strEndFind As String) As String
SubStr = ""
Try
If strSource.Trim.Length > 0 And strStartFind.Trim.Length And strEndFind.Trim.Trim.Length > 0 Then
Dim intStartStr As Integer = 0, intEndStr As Integer = 0
intStartStr = strSource.IndexOf(strStartFind) + strStartFind.Trim.Length
intEndStr = strSource.IndexOf(strEndFind)
SubStr = strSource.Substring(intStartStr, intEndStr - intStartStr)
End If
Return SubStr
Catch ex As Exception
Throw ex
End Try
End Function
weilu0328 2008-12-06
  • 打赏
  • 举报
回复
楼上各位都是right,可以任选一种试试看;
yanlongwuhui 2008-12-06
  • 打赏
  • 举报
回复
字符串中不一定有“-”时,参考如下:
Dim strTemp As String
Dim intPos As Integer
strTemp = "asdf152-s-01"
intPos = strTemp.LastIndexOf("-")
If intPos < 0 Then
Else
strTemp = strTemp.Substring(0, strTemp.LastIndexOf("-"))
End If
bw555 2008-12-06
  • 打赏
  • 举报
回复
        Dim str As String = "asdfasdfa-sdf"
Dim a As String() = str.Split("-")
MsgBox(Mid(str, 1, Len(str) - Len(a(a.Length - 1)) - 1))
yanlongwuhui 2008-12-06
  • 打赏
  • 举报
回复
参考如下
strTemp = "asdf152-s-01"
MsgBox(strTemp.Substring(0, strTemp.LastIndexOf("-")))
长沙三毛 2008-12-06
  • 打赏
  • 举报
回复
            string str = "abc-1-2";
int n = str.LastIndexOf('-');
string s = str.Substring(0, n);
MessageBox.Show(s);
呵呵,不好意思给出了C#代码。但关键是使用LastIndexOf方法。
wuyq11 2008-12-06
  • 打赏
  • 举报
回复
通过substring,split或正则表达式实现

16,717

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧