-8

Is there any way to extract an integer from a position in a string? Each string will have the word "documents" after it (e.g. "There are 22 documents").

HireThisMarine
  • 241
  • 5
  • 12
JW111
  • 1
  • 3
  • will there be more than 1 integer in the string? – user1666620 Jan 11 '16 at 17:11
  • 1
    Have you tried anything at all? Even googling will give you pretty fast answers. – Camilo Terevinto Jan 11 '16 at 17:12
  • 2
    `IndexOf` function `SubString` function Come on @JW111 this is 2016 and everyone should know how to initiate a simple google search in all due respect.. – MethodMan Jan 11 '16 at 17:12
  • 2
    Possible duplicate of [Find and extract a number from a string](http://stackoverflow.com/questions/4734116/find-and-extract-a-number-from-a-string) this was the first result for my google of "find integer in string c#": https://www.google.ie/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=find+integer+in+string+c%23 – user1666620 Jan 11 '16 at 17:12
  • Use a regex, that would be the safest way – Gusman Jan 11 '16 at 17:13
  • Try regex if it is only integer in string. `Regex.Match(str, @"\d");` Or use following if your number is placed on a specific `index` . `Regex.Match(str.Substring(index), @"^\d");` – tchelidze Jan 11 '16 at 17:13
  • Do you want to remove the integers from the string, or do you want to copy this specific data and use it elsewhere? – HireThisMarine Jan 11 '16 at 17:17

1 Answers1

1

here is something you can use and play around with. If your data always contains the words There is documents then you have There is 22 documents you will return the integer(s)

string asplitStr = "There is 22 documents";
var aspltLsts = asplitStr.Split(new[] { "There is", "documents" }, StringSplitOptions.RemoveEmptyEntries);

A better solution using Linq you can do the following as well

string asplitStr = "There is 22 documents";
string resultStr = new String(asplitStr.
     Where(x => Char.IsDigit(x)).ToArray());

Returns " 22 "

MethodMan
  • 18,625
  • 6
  • 34
  • 52