-1

i have the following string "USB SERIAL PORT (COM6)" i want to get COM6 out of this.

This is the code i am trying to use

string.substring(3, string.length - 1) 

something of that sort. Havent been able to get anything.

TheNoob
  • 185
  • 1
  • 12
  • Study the docs for [substring](https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx) and get simple examples working. You should always do this, don't just guess. In particular, why would startIndex be 3?! – Andy G Dec 28 '17 at 20:29
  • @AndyG Okay, should i find the index of the brackets and then work from there? – TheNoob Dec 28 '17 at 20:30
  • Yes! You will at least get more of a response if you demonstrate such efforts. – Andy G Dec 28 '17 at 20:31
  • @AndyG I got it,,, Thanks for the constructive criticism :) – TheNoob Dec 28 '17 at 20:36
  • https://stackoverflow.com/q/19840811/1070452 Please read [ask] and take the [tour] – Ňɏssa Pøngjǣrdenlarp Dec 28 '17 at 20:42
  • @Plutonix i am past that step :) Thanks tho.. I already have the names just trying to find the substring. I actually wanted the manufacturer information for each port... – TheNoob Dec 28 '17 at 20:44
  • No, you skipped some steps – Ňɏssa Pøngjǣrdenlarp Dec 28 '17 at 20:47
  • @Plutonix Okay Sir. Also i have asked a couple of questions prior to this, I was just exhausted and wanted an easy answer.I think i am good with the tour and How to Ask( I appreciate you looking out for me though). – TheNoob Dec 28 '17 at 21:00

1 Answers1

1

You'd be better off using the last occurrence of ( as an index, in case one day your string changes format, or com6 is longer (com10):

Dim lastBra as Integer = myString.LastIndexOf("("c)
Dim lastKet as Integer = myString.LastIndexOf(")"c)

Dim subs as String = myString.Substring(lastBra + 1, lastKet - lastBra - 1)

It's lastBra+1 because we want the character after the open bracket as a start. The length to substring is the bracket indexes, less one because we don't want the last bracket to be included:

enter image description here

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • Change the last line to `myString.Substring(lastBra + 1, lastKet - lastBra)` – TheNoob Dec 28 '17 at 20:38
  • I disagree, see the edited in screenshot. For a string of `abc(def)` lastBra would be 4, lastKet would be 8, we want the string from 5, length 3, but your suggestion of lastKet - lastBra is 8-4, which is 4, not 3 (assuming VB is in 1 based index mode. If it's in 0 based index mode all these numbers change by 1, but the overall math is the same) – Caius Jard Dec 28 '17 at 20:53
  • Yes! I am sorry i was adding +1 to lastBra itself – TheNoob Dec 28 '17 at 20:56
  • It's good to challenge, made me double check and deliver a better answer I think, thanks! – Caius Jard Dec 28 '17 at 20:59