I have a string variable like test10015, i want to get just the 4 digits 1001, what is the best way to do it? i"m working in asp.net c#
Asked
Active
Viewed 2,869 times
0
-
2All the answers proposed so far assume the digits will be in a certain position within the string, and would break if the string was instead something like `"a1234b"`. Please provide more a specific explanation on *exactly* what kinds of inputs you expect and what output you would like. Also, please show us what you've tried so far. – p.s.w.g May 08 '14 at 05:14
-
Thank you, but my digits are in a certain position. – El Sande May 08 '14 at 05:19
-
try this. it will work for you: string s = "test10015"; string newstring = s.Substring(s.Length - 5, 4); Console.WriteLine(newstring); – Running Rabbit May 08 '14 at 05:24
4 Answers
2
With Linq:
var expected = str.Skip(4).Take(4);
Without Linq:
var expected = str.Substring(4,4);

Sriram Sakthivel
- 72,067
- 7
- 111
- 189
0
string input = "test10015";
string result = input.Substring(4, 4);

Vivek Jain
- 3,811
- 6
- 30
- 47

Sajeetharan
- 216,225
- 63
- 350
- 396
-
This is wrong. The first parameter is the position in the original string, which you've set as the first character. – Robert Harvey May 08 '14 at 05:12
0
Select the first four digits in your string:
string str = "test10015";
string strNum = new string(str.Where(c => char.IsDigit(c)).Take(4).ToArray());

Amir Popovich
- 29,350
- 9
- 53
- 99
-
-
-
1Well then instead of criticizing everyone else, it maybe more productive if you provided your own solution. – Ben May 08 '14 at 05:16
-
-
substring is good for this spec. case.. I guess he wanted something more generic..but that's just a guess.. – Amir Popovich May 08 '14 at 05:16
0
You can use String.Substring Method (Int32, Int32). You can subtract 5 from from the length to start from your required index. Make sure the format of string remains the same.
string res = str.Substring(str.Length-5, 4);

Adil
- 146,340
- 25
- 209
- 204