1

I need to extract only the last part of a string after a / character.

I have tried with LastIndexOf, but it fails.

Any solution?


Attempt

var strDiv2 = tbxAff.Substring(tbxAff.IndexOf(" / "), /*value is missing*/ );
dblDiv2 = Convert.ToDouble(strDiv2);`
        
Douglas
  • 53,759
  • 13
  • 140
  • 188
DanyDC
  • 73
  • 1
  • 14
  • Welcome to Stackoverflow! Please edit your question and insert C# code here. However, this http://stackoverflow.com/questions/15667927/how-to-keep-the-delimiters-of-regex-split will help you. – Ravimallya Dec 12 '15 at 11:10
  • 1
    Post your code as text, **not** an image. That'll greatly improve your chances of getting an answer. Also, you can get the text from the TextBox so your question is really "*Extract the last part of a string*" – Wai Ha Lee Dec 12 '15 at 11:11
  • Your problem has nothing to do with TextBoxes, Get the string out of the box and use string functions to manipulate it. Have you tried string.Split? – anhoppe Dec 12 '15 at 11:15
  • LastIndexOf is way to go here, show us your attempt with LastIndexOf – CSharpie Dec 12 '15 at 11:22
  • What error message are you getting? – Peter Smith Dec 12 '15 at 11:22

4 Answers4

2

You can just omit the second parameter. This would call the Substring(int) overload, which returns a substring that starts at a specified character position and continues to the end of the string.

string strDiv2 = tbxAff.Text.Substring(tbxAff.Text.IndexOf("/") + 1);

Also, if you're parsing the extracted substring as a double, you presumably want to exclude the / separator character.

Douglas
  • 53,759
  • 13
  • 140
  • 188
0

Use the String.Split() function:

string[] y = tbxAff.Text.Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);

Then use it like this:

string strDiv2 = y[1] // Second Part
dblDiv2 = Convert.ToDouble(strDiv2);
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
0

string clientSpnd = textBox1.Text.Substring(textBox1.Text.LastIndexOf(' ') + 1);

0

Here is an extension method which will do safety checking:

public static class StringExtensions
{
     public static string LastPartOfStringFrom(this string str, char delimiter )
     {
         if (string.IsNullOrWhiteSpace(str)) return string.Empty;

         var index = str.LastIndexOf(delimiter);

         return (index == -1) ? str : str.Substring(index + 1);
     }
}
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122