2010-02-24 92 views

回答

0

如果你想在你可以使用LINQ查询字符串中的最后一个字母字符,如(C#):

var d = from c in myString.ToCharArray().Reverse() 
       where Char.IsLetter(c) 
       select c; 
return d.First(); 
+0

请参阅问题:VB字符串。 – NTDLS 2010-02-24 16:01:12

0

string.Substring(string.Length - 2,1);

2

对不起它已经有一段时间,因为我做VB所以这可能不会是完美的(并且可能是C#和VB的混合物),但你的想法:

Dim s = "V1245-12V0" 
Dim lastButOneLetter = String.Empty 

If s.Length > 1 Then 
    'Can only get the last-but-one letter from a string that is minimum 2 characters 
    lastButOneLetter = s.Substring(s.Length - 2, 1) 
Else 
    'do something if string is less than 2 characters 
End If 

编辑:固定为编译VB .NET代码。

+0

+1长度检查。 -1表示使用子字符串。 – Joel 2010-02-24 16:06:39

+0

@Joel - 为什么-1使用子字符串?它比Strings.GetChar ...或mystring(...)更清晰,更明显 – 2010-02-24 16:18:40

+0

我认为OP在询问“Char”时非常清楚。由于我没有使用子字串downvote其他人,我会给你。值得记住做长度检查。 – Joel 2010-02-24 17:12:58

0

使用Substring上包含“V1245-12V0”

s.Substring(s.Length - 2, 1); 
+0

请问我为什么这是downvoted?正如其他人曾经以类似的形式提到过这种... ... downvote和不留下评论被认为是非常粗鲁和无知,这是违背SO的精神。如果我低估了你的回答,不发表评论,你不知道是什么原因......你会如何? – t0mm13b 2010-02-24 16:12:33

+1

这可能来自Joel Potter不同意使用子字符串。如果你注意到使用Substring的每个答案都被低估了,即使它是基于我们提供的信息的完美解决方案。downvote国际海事组织是一个答案,不解决原来的问题,不是因为某人的个人喜好。 – 2010-02-24 16:25:06

+0

@安迪:我发表了评论,他的回答.... – t0mm13b 2010-02-24 16:39:56

-1

你可以有自己的功能,如

Function Left(ByVal str as string, byval index as integer) As String 

    Left=str.Substring(0,index); 
End Function 

Function Right(ByVal str as string, byval index as integer) As String 

    Right=str.Substring(str.Length-index) 
End Function 

,并利用它们来获得你所需要的字符串s。

+0

This _is_ VB:你已经有'Left','Mid'和'Right'了。 – 2016-08-27 18:28:02

1
Dim secondToLastChar As Char 
secondToLastChar = Microsoft.VisualBasic.Strings.GetChar(mystring, mystring.Length - 2) 

http://msdn.microsoft.com/en-us/library/4dhfexk4(VS.80).aspx

或者只记得任何字符串是字符数组;

secondToLastChar = mystring(mystring.Length - 2) 
+0

@Joel Potter - 那你为什么不修改这个问题来指定不使用子字符串,而是尽管提出了模糊的问题来降低每个人的意见!你有足够的代表点来做到这一点! – t0mm13b 2010-02-24 16:39:20

+0

我没有倒下每个人。我只是提出了最好的解决方案(Coehoorn's)。 – Joel 2010-02-24 17:06:36

0

是不是很难?

dim mychar as string 
dim yourstring as string 
yourstring="V1245-12V0" 
mychar=yourstring.Substring(yourstring.Length - 2, 1) 
4

不要使用子得到的只是一个字符

Dim MyString As String = "V1245-12V0" 
Dim MyChar As Char = MyString(MyString.Length - 2) 
+0

我同意。看不到为什么80%的答案选择了这种方法。 – Joel 2010-02-24 16:04:00

+0

基于OP后来想用这个角色做什么更灵活。我会使用字符串来支持字符串的唯一原因是,除非我绝对确信它将始终是一个必需的字符,并且有人不会说“实际上我现在想要字符串中的2个字符”,或者我绝望地缺乏内存,比如嵌入式设备。 – 2010-02-24 16:29:34

0

这里是一个VB的解决方案:

Dim text = "V1245-12V0" 
Dim v = Left(Right(text, 2), 1) 

你做需要检查的text长度,除了你的语义是什么你想为空发生(和Nothing )和单个字符字符串。

相关问题