-2

I have a string that contains something like this "'asd asd asd / * ... asd ' asd..." I just want to retrieve only the value that starts from ' and ends the same character '. So from that string the value will be "asd asd asd / * ... asd"

I tried with the code below but it doesn't work.

string HDtext = new string(TextChar.SkipWhile(c => !Char.IsSymbol(c))
                                   .TakeWhile(c => Char.IsLetter(c) ||
                                                   c == '*' ||
                                                   c == '/' ||
                                                   c == ' ')
                                   .ToArray());

Does anybody know how to retrive it correctly ?

Dante May Code
  • 11,177
  • 9
  • 49
  • 81
Paweld_00
  • 81
  • 8
  • 1
    [`Substring`](https://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.110%29.aspx) and [`IndexOf`](https://msdn.microsoft.com/en-us/library/system.string.indexof%28v=vs.110%29.aspx) – Sami Kuhmonen Aug 12 '15 at 08:44

4 Answers4

3

I would use Regex here

string input = "'asd asd asd / * ... asd ' asd...";
var output = Regex.Match(input, @"'(.+?)'").Groups[1].Value;
Eser
  • 12,346
  • 1
  • 22
  • 32
1

String.Split would be a option

string input = "'asd asd asd / * ... asd ' asd...";
string result = input.Split('\'')[1];
fubo
  • 44,811
  • 17
  • 103
  • 137
  • What if input doesn't have a `'` character. One solution: `input.Split('\'').Skip(1).FirstOfDefault()` – tafia Aug 12 '15 at 08:55
0

you can get the index of the first and last occurrence of your desired char and then just take the substring between them. Like this, for example:

var __text = "'asd asd asd / * ... asd' asd...";
var __startIndex = __text.IndexOf("'") + 1;
var __length = __text.LastIndexOf("'") - __startIndex;

var __subString = __text.Substring(__startIndex, __length);  
DangerousDetlef
  • 371
  • 2
  • 11
0

If you want to use LINQ:

string result = new string(str.SkipWhile(c => c != '\'')
                              .Skip(1)
                              .TakeWhile(c => c != '\'').ToArray());

If there are more than 2 ' chars and you want to get everything between the first and the last:

string result = new string(str.SkipWhile(c => c != '\'').Skip(1)
                              .Reverse()
                              .SkipWhile(c => c != '\'').Skip(1)
                              .Reverse()
                              .ToArray());
w.b
  • 11,026
  • 5
  • 30
  • 49