1

I'm trying to remove the last part of the string to make it more presentable. The string looks like this

Stringname.number.RemainingStringTobeRemoved

Is there a way to remove the last part without using string.Substring(0,string.Length-10)? I want it to be dynamic, the string I'll be removing is not a constant number.

My initial idea was to use delimiter to identify the starting point of the part I want to remove.

ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176

3 Answers3

1

My initial idea was using delimiter to identify the starting point of the part I want to remove.

That's a good idea if your string is always the same format and the substring you want to remove does not contain that delimiter. Take a look at LastIndexOf.

Spoiler:

Dim s = "Stringname.number.RemainingStringTobeRemoved"
Dim r = s.Substring(0, s.LastIndexOf("."))

sloth
  • 99,095
  • 21
  • 171
  • 219
  • What if I want to remove everything after the 2nd "."? – user2918970 Jul 04 '14 at 08:12
  • @user2918970 you could use a function that finds the nth occurrence of a string inside another one like described [here](http://stackoverflow.com/a/187394/142637) and use that together with `Substring` – sloth Jul 04 '14 at 08:23
0

Using a delimiter is one way. You can use the Split method to split the string into parts at the ..

Dim FullString As String = "Stringname.number.RemainingStringTobeRemoved"
Dim StringParts() As String = Strings.Split(FullString, ".", 3)
Return StringParts(0) & StringParts(1)

The Split method returns an array of String that contains the parts. The array will contain the following items

  • Stringname
  • number
  • RemainingStringTobeRemoved

The delimiters are omitted.

Jens
  • 6,275
  • 2
  • 25
  • 51
0

You can use Split to achieve this

String s = "Stringname.number.RemainingStringTobeRemoved"
Dim words As String() = s.Split(New Char() {"."c})
String RequiredString = words(0) & words(1)

The RequiredString is what you need

Ajit Vaze
  • 2,686
  • 2
  • 20
  • 24