0

Lets say I have a string:

string a = "abc&dcg / foo / oiu";

now i would like the output to be

"abc&dcg"

i have tried:

string output= a.Substring(a.IndexOf('/'));

but it returns the last part not the first part

I have tried trim() as well, but doesn't provide me with the results.

waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
  • thanks for the quick anwser guys, but lets say between the g and / there is a space, how do i eleminate that with the same one line of code? thanks – user3847775 Jul 28 '14 at 02:00
  • thanks for the anwsers guys, and TrimEnd(' '); eliminate the last white space of the output – user3847775 Jul 28 '14 at 02:20

3 Answers3

0

Try

string output;
if (a.IndexOf('/')>=0) { output = a.Split('/')[0].Trim() };

This wil prevents error case a doesn't contains any /

Nizam
  • 4,569
  • 3
  • 43
  • 60
  • I have changed to `Trim()`since replace would replace all spaces, including that ones separating the words before `/`(if exists) – Nizam Jul 28 '14 at 02:02
  • what if is something like this abc def & sdf / jfdkjf , and i would like to just get abc def & sdf, which eliminates the last space only, thanks!! – user3847775 Jul 28 '14 at 02:15
  • It will returns abc def & sdf. Isn't right? Observe that I perceived this could happen with `replace` and changed my answer to `Trim` – Nizam Jul 28 '14 at 02:17
  • i think trimend() would do the trick – user3847775 Jul 28 '14 at 02:18
  • yah it did, thanks for the help – user3847775 Jul 28 '14 at 02:19
  • The difference between trim and trimend is that the first removes spaces from begin and end, while the second onle removes the spaces from the end. – Nizam Jul 28 '14 at 02:24
0

Try this:

string result = a.Split('/')[0].Trim();

The split operation will give you the 3 substrings separated by '/' and you can choose whichever ones you want by specifying the index.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63
0

Try this one

 string a = "abc&dcg / foo / oiu";
 string output = a.Substring(0, a.IndexOf("/"));
 Console.WriteLine(output);

It will show

abc&dcg 
NTK88
  • 573
  • 1
  • 6
  • 12