Reputation: 43
How can I trim some string until I got three specific characters which are the same as, for example, "xyz". To be precise I will give an example:
Dim String1 as String = "GunsAndRosesWelcomeToTheJungle"
Dim String2 as String = "DontCry"
Dim ResultString as String
I need to remove everything from right until I get "moc" (reverse "com")
in String1
and add string2
to get ResultString
.
The ResultString should be: "GunsAndRosesWelDontCry"
Upvotes: 0
Views: 409
Reputation: 21905
You can try this way,
Dim String1 As String = "GunsAndRosesWelcomeTocomeThecomJunglecom"
Dim String2 As String = "DontCry"
Dim ResultString As String
Dim ar As String() = String1.Split("com")
ResultString = ar(0) & String2
Upvotes: 0
Reputation: 30813
You could use String.IndexOf
and the String.Substring
and start from in front to solve it:
Dim String1 as String = "GunsAndRosesWelcomeToTheJungle"
Dim String2 as String = "DontCry"
Dim index = String1.IndexOf("com")
Dim ResultString as String = String1.Substring(0, index) + String2
Edit:
If both the substring input and the string need to be reversed for one reason or another, I would introduce a reverse string function like this
Private Function Reverse(Val As String) As String
Dim charArray As Char() = Val.ToCharArray()
Array.Reverse(charArray)
Return New String(charArray)
End Function
And then use it like this
Dim String1 As String = "GunsAndRosesWelcomeToTheJungle"
Dim String2 As String = "DontCry"
Dim index = String1.Length - Reverse(String1).IndexOf(Reverse("com")) - ("com").Length
Dim ResultString As String = String1.Substring(0, index) + String2
Else, we can use String.LastIndexOf
Dim String1 as String = "GunsAndRosesWelcomeToTheJungle"
Dim String2 as String = "DontCry"
Dim index = String1.LastIndexOf("com")
Dim ResultString as String = String1.Substring(0, index) + String2
Upvotes: 2