How can I trim MyString to be MyStr?
Thanks, google failed again :(
YourString.Left(YourString.Length-4)
or:
YourString.Substring(0,YourString.Length-4)
Rob's answer is mostly correct but the SubString solution will fail whenever the string has less than 4 characters in it. If the length goes past the end of the string an exception will be thrown. The following fixes that issue
Public Function TrimRight4Characters(ByVal str As String) As String
If 4 > str.Length Then
return str.SubString(4, str.Length-4)
Else
return str
End if
End Function
c#
string str = "MyString";
Console.WriteLine(str.Substring(0, str.Length - 3));
vb.net
dim str as string = "MyString"
Console.WriteLine(str.Substring(0, str.Length - 3))
vb.net (with VB6 style functions)
dim str as string = "MyString"
Console.WriteLine(Mid(str, 1, len(str) - 3))
This is what I used in my program (VB.NET):
Public Function TrimStr(str As String, charsToRemove As String)
If str.EndsWith(charsToRemove) Then
Return str.Substring(0, str.Length - charsToRemove.Length)
Else
Return str
End If
End Function
Usage:
Dim myStr As String = "hello world"
myStr = TrimStr(myStr, " world")
This is my first answer. Hope it helps someone. Feel free to downvote if you don't like this answer.
Related
I have a comma delimited file with sample values :
1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT
Question : how to replace the comma in the last column which is "AAA,TEXT"
The result should be this way:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
There is an overload of String.Split which takes an argument telling it the maximum number of parts to return. You could use it like this:
Option Infer On
Option Strict On
Module Module1
'TODO: think up a good name for this function
Function X(s As String) As String
Dim nReturnParts = 7
Dim parts = s.Split({","c}, nReturnParts)
If parts.Count < nReturnParts Then
Throw New ArgumentException($"Not enough parts - needs {nReturnParts}.")
End If
parts(nReturnParts - 1) = parts(nReturnParts - 1).Replace(",", "")
Return String.Join(",", parts)
End Function
Sub Main()
Dim s() = {"1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT",
"1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT",
"1,1076103,22-NOV-16,21051169,50,1083,C,C,C,TEXT"}
For Each a In s
Console.WriteLine(X(a))
Next
Console.ReadLine()
End Sub
End Module
Outputs:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT
1,1076103,22-NOV-16,21051169,50,1083,CCCTEXT
Is simple, but learn a bit how to use string ;)
Public Function MDP(strWork As String)
Dim splitted() As String = strWork.Split(","c)
Dim firsts As New List(Of String)
For i As Integer = 0 To splitted.Count - 3
firsts.Add(splitted(i))
Next
Dim result As String = System.String.Join(",", firsts)
Return result & "," & splitted(splitted.Count - 2) & splitted(splitted.Count - 1)
End Function
Then call with:
Dim finished As String = MDP("1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT")
I created a simple function designed to remove a string of characters from another string and replace it with what ever string the user wants (or no string as a default)
Private Function RemoveString(scontainer As String, Optional rcontainer As String = "", Optional rstring As String = "") As String
Dim container As String = scontainer
Dim tcontainer As String
If InStr(container, rcontainer) <> 0 Then
Do While (InStr(container, rcontainer) <> 0)
tcontainer = Microsoft.VisualBasic.Left(container, InStr(container, rcontainer) - 1)
tcontainer = tcontainer & rstring & Microsoft.VisualBasic.Right(container, (Len(container) - (InStr(container, rcontainer) + 2)))
container = tcontainer
Loop
RemoveString = container 'return modded string
Else
RemoveString = scontainer 'return string as is
End If
End Function
The problem is:
While this is suppose to be a general use function, I really need it to be concerned with 2 different strings
%20
amp;
the function works perfectly for the %20 situation but it leaves the semi-colon behind for the amp; string. Any ideas why this might be?
Do I get you right ?
You want to replace a certain char sequence in your string with another char sequence or just delete it.
If thats the case you could use String.Replace(oldValue As String, newValue As String) As String
Dim startString as String = "%20 amp;"
Dim resultString as String = startString.Replace("%20 ",String.Empty)
resultString = resultString.Replace(";",String.Empty)
After these lines resultString would be "amp"
This question already has answers here:
Best way to reverse a string
(51 answers)
Closed 9 years ago.
I am using this function to reverse text but I am having a little issue with speed.
for testing I have 130,000 characters text and its taking about 10 seconds. is it possible to speed it up? This questions is different than C# as its a vb.net
Function ReverseString(ByRef strString As String) As String
Dim NextChr, TempString As String, StringLength, Count As Integer, NewString As String = Nothing
TempString = strString
StringLength = Len(TempString)
Do While Count <= StringLength
Count = Count + 1
NextChr = Mid(TempString, Count, 1)
NewString = NextChr & NewString
Loop
ReverseString = NewString
End Function
Try this:
Function Reverse(ByVal value As String) As String
' Convert to char array.
Dim arr() As Char = value.ToCharArray()
' Use Array.Reverse function.
Array.Reverse(arr)
' Construct new string.
Return New String(arr)
End Function
Source: dot net perls
Maybe something along the lines of http://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx?
in VB:
Dim TestString As String = "ABCDEFG"
' Returns "GFEDCBA".
Dim revString As String = StrReverse(TestString)
Function ReverseString(ByRef strString As String) As String
Dim charArray As Char() = strString.ToCharArray()
Array.Reverse(charArray )
Dim strReversed As New String(charArray )
ReverseString = strReversed
End Function
I would convert your string to a Character Array, then just call Array.Reverse.
I just tried this and it ran in: 0.862 seconds with a string that had 26,673,152 characters. Granted I'm on a pretyy fast PC but stil.
As it was said in other answers - it is better to use special function for this: StrReverse
but, if you want to have your own function, you can use this one, it should be faster:
Function ReverseString(ByRef strString As String) As String
Dim builder As New System.Text.StringBuilder(strString.Length)
Dim index As Integer = strString.Length - 1
While index >= 0
builder.Append(strString.Chars(index))
index = index - 1
End While
ReverseString = builder.ToString
End Function
What will be the easiest way to convert a string to decimal?
Input:
a = 40000.00-
Output will be
40,000.00-
I tried to use this code:
Dim a as string
a = "4000.00-"
a = Format$(a, "#,###.##")
console.writeline (a)
Use Decimal.Parse to convert to decimal number, and then use .ToString("format here") to convert back to a string.
Dim aAsDecimal as Decimal = Decimal.Parse(a).ToString("format here")
Last resort approach (not recommended):
string s = (aAsDecimal <0) ? Math.Abs(aAsDecimal).ToString("##,###0.00") + "-" : aAsDecimal .ToString("##,###0.00");
You will have to translate to Visual Basic.
For VB.NET:
CDec(Val(string_value))
For example,
CDec(Val(a))
The result will be 40000D or if the value for a = "400.02" then it will be 400.02D.
Use Decimal.TryParse
Dim a as string
Dim b as Decimal
If Decimal.TryParse(a, b) Then
a = b.ToString("##,###.00")
Else
a = "can not parse"
End If
The following works fine for me, but I don't know whether it is correct or not.
double a = 40000.00;
a = double.Parse(a.ToString("##,###.00"));
MessageBox.Show(a.ToString("##,###.00"));
Sub Main()
Dim convert As Func(Of String, Decimal) = _
Function(x As String) Decimal.Parse(x) ' This is a lambda expression.
Dim a = convert("-16325.62")
Dim spec As String = "N"
Console.WriteLine("{1}", spec, a.ToString(spec))
'Console.ReadLine() ' Uncomment to see value in Console output.
End Sub
Dim D# = CDec(TextBox1.Text) '//convert string to decimal with short
This code works, but it is quite long:
Dim a as string
Dim b as decimal
a = "4000.00-"
b = a
If b >= 0 then
console.writeline (b.ToString("##,###.00"))
Else
b = Math.Abs(b)
console.writeline (b.ToString("##,###.00") & "-")
End if
How do I find last but one character in a vbstring
for e.g. In the string V1245-12V0 I want to return V
Don't use substring to get just one character
Dim MyString As String = "V1245-12V0"
Dim MyChar As Char = MyString(MyString.Length - 2)
Sorry it's been a while since I did VB so this may not be perfect (and is probably a mixture of C# and VB) but you get the idea:
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
EDIT: fixed to be compilable VB.NET code.
Dim secondToLastChar As Char
secondToLastChar = Microsoft.VisualBasic.Strings.GetChar(mystring, mystring.Length - 2)
http://msdn.microsoft.com/en-us/library/4dhfexk4(VS.80).aspx
Or just remember that any string is an array of chars;
secondToLastChar = mystring(mystring.Length - 2)
If you want to get the last alpha-character in a string you could use a LINQ query such as (C#):
var d = from c in myString.ToCharArray().Reverse()
where Char.IsLetter(c)
select c;
return d.First();
string.Substring(string.Length - 2, 1);
Was it difficult?
dim mychar as string
dim yourstring as string
yourstring="V1245-12V0"
mychar=yourstring.Substring(yourstring.Length - 2, 1)
Use the Substring on the string s which contains 'V1245-12V0'
s.Substring(s.Length - 2, 1);
Here's a VB solution:
Dim text = "V1245-12V0"
Dim v = Left(Right(text, 2), 1)
You do not need to check the length of text, except for your semantics as to what you want to happen for empty (and Nothing) and single character strings.
You can have your own functions like
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
And use them to get what you need.