2012-03-05 46 views
1

就像标题所说的那样;我想用Mid这样的东西(stringName,startIndex,[integerLength]),但是不是第三个参数取得字符串长度,我希望它取得结束字符索引。因此,在像为例此我可以使用什么方法来检索使用两个字符索引的字符串?

alphabet = "ABCDEFG" 
partial = *method I want to use*(alphabet, 2, 4) 'partial would equal "BC" 

(原谅我,如果我的索引号是关闭的,但我希望你明白我的意思。)

难道这样的事情在VB.NET存在吗?

回答

2

你要使用String.Substring

http://msdn.microsoft.com/en-us/library/aka44szs.aspx#Y0

dim alphabet as string = "ABCDEFG" 
'partial is a reserved word! 
'1,2 is the correct parameters to get 'BC' 
dim partialString as string = alphabet.Substring(1, 2) 'partial would equal "BC" 

编辑 - 哇,你想要做的开始索引,StopIndex没有开始索引,长度。只需应用一点数学。

dim startIndex as integer = 1 
dim stopIndex as integer = 3 

'partial would equal "BC" 
dim partialString as string = _ 
    alphabet.Substring(startIndex , stopIndex-startIndex) 

我会把它包装在一个字符串的扩展方法,给它一个新的名字当然。

+0

好的,谢谢!因此,从我得到的答案,我推断这没有*内置*方法?不是我无法做数学,只是,呃...我很懒惰:) – Quintis555 2012-03-05 22:11:08

+0

@ Quintis555:我想知道,直到我意识到你不再需要弄清楚如何处理'3,2'当与长度一起工作时。 – Guvante 2012-03-05 22:34:14

-1
targetstring=alphabet.Substring(2,4) 

上面应该工作..

1

只需使用MID,数学的长度是很容易的(length = endIndex - startIndex):

part = Mid(alphabet, 2, 4-2) 

你也可以实现与子串同样的事情(使用基于0的索引而不是1基于):

part = alphabet.Substring(1, 3-1); 
+0

它应该是(2,4) – Teja 2012-03-05 21:52:24

+0

@Venk - 不,它不应该。这就是为什么你错了。 String.Substring的第二个参数是** length **而不是endIndex。 – 2012-03-05 21:54:17

相关问题