how do i convert string numbers to int - c#

I want just numbers.
string str_a = "a1bc2d23ghj2";
int in_b = convert.toint32(str_a); // doesn't works
I want the output of in_b to be: 12232

string str_a = "a1bc2d23ghj2";
string str_digits_only = new String(str_a.Where(char.IsDigit).ToArray());
int in_b = Convert.ToInt32(str_digits_only);

StringBuilder builder = new StringBuilder();
foreach (char c in str_a)
{
if (Char.IsDigit(c))
{
builder.Append(c);
}
}
int in_b = Int32.Parse(builder.ToString());

It doesn't work because the input string is not a valid number and also because you have to use Convert.ToInt32(string) or int.Parse(string).
If you want to extract only the numbers from a string you could use LINQ:
string onlyNumbers = (from ch in str_a
where char.IsDigit(ch)
select ch.ToString()).Aggregate((a, b) => a + b);
int in_b = int.Parse(onlyNumbers);

my solution for this would be to check the char codes of the characters in your string. Select all numbers and convert them:
var str_a = "a1bc2d23ghj2";
var in_b = Convert.ToInt32(string.Join(string.Empty,str_a.Where(x => x >= 48 && x <= 57)));

int num = Convert.ToInt(System.Text.Regex.Replace(stra, "[^0-9]", string.Empty));

Have a look at the tryparse method.

Related

How to convert a string with comma to integer in C#

For example I have a string "99,999 ABC XYZ"
Now I want to convert to integer "99999"
I have made a code that worked:
var regex = new Regex("[A-z]");
linksOnPage = regex.Replace(linksOnPage, "");
regex = new Regex(" ");
linksOnPage = regex.Replace(linksOnPage, "");
int noPage = int.Parse(regex.Replace(linksOnPage, ""),
NumberStyles.AllowThousands);
But I feel it's not good enough, can anyone help me to make it shorter?
This Regex will remove all the letters and spaces:
var regex = new Regex(" |[A-z]");
linksOnPage = regex.Replace(linksOnPage, "");
You could use int.Parse and add the NumberStyles.AllowThousands flag:
int num = int.Parse(linksOnPage , NumberStyles.AllowThousands);
Or int.TryParse letting you know if the operation succeeded:
int num;
if (int.TryParse(linksOnPage , NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out num))
{
// parse successful, use 'num'
}
Or you can also try this:
int num = int.Parse(linksOnPage.Replace(",", ""));
This would be my approach, it's not really shorter though:
public static void Main(string[] args)
{
string input = "99,999 ABC XYZ";
var chars = input.ToCharArray().ToList();
var builder = new StringBuilder();
foreach (var character in chars)
{
if (char.IsNumber(character))
builder.Append(character);
}
int result = 0;
int.TryParse(builder.ToString(), out result);
Console.WriteLine(result);
Console.ReadKey();
}
you could do something like this:
int? ParseIntFromString( string s )
{
Match m = rxInt.Match(s) ;
int? value = m.Success ? int.Parse( m.Value , NumberStyles.AllowLeadingSign|NumberStyles.AllowThousands ) : (int?)null ;
return value ;
}
static Regex rxInt = new Regex( #"^-?\d{1,3}(,\d\d\d)*");
the return value is null if no integer value was found and the parsed value if it was.
Note that the match is anchored at start-of-string via ^; if you want to match an number anywhere in the string, simply remove it.
You could also kick it old-school and do something like this:
public int? ParseIntFromString( string s )
{
bool found = false ;
int acc = 0 ;
foreach( char c in s.Where( x => char.IsDigit )
{
found = true ;
acc += c - '0' ;
}
return found ? (int?)acc : (int?) null ;
}

How to Get Data from index of String

I'm new in c#. and I have some Question...
I have String following this code
string taxNumber = "1222233333445";
I want to get data from This string like that
string a = "1"
string b = "2222"
string c = "33333"
string d = "44"
string e = "5"
Please Tell me about Method for get Data From String.
Thank You Very Much ^^
Use the String.Substring(int index, int length) method
string a = taxNumber.Substring(0, 1);
string b = taxNumber.Substring(1, 4);
// etc
Oh well, the best I can come up with is this:
IEnumerable<string> numbers
= taxNumber.ToCharArray()
.Distinct()
.Select(c => new string(c, taxNumber.Count(t => t == c)));
foreach (string numberGroup in numbers)
{
Console.WriteLine(numberGroup);
}
Outputs:
1
2222
33333
44
5
This can also do , you dont need to fix the no of characters, you can check by changing the no of 1's , 2's etc
string taxNumber = "1222233333445";
string s1 = taxNumber.Substring(taxNumber.IndexOf("1"), ((taxNumber.Length - taxNumber.IndexOf("1")) - (taxNumber.Length - taxNumber.LastIndexOf("1"))) + 1);
string s2 = taxNumber.Substring(taxNumber.IndexOf("2"), ((taxNumber.Length - taxNumber.IndexOf("2")) - (taxNumber.Length - taxNumber.LastIndexOf("2"))) + 1);
string s3 = taxNumber.Substring(taxNumber.IndexOf("3"), ((taxNumber.Length - taxNumber.IndexOf("3")) - (taxNumber.Length - taxNumber.LastIndexOf("3"))) + 1);
You can use Char.IsDigit to identify digits out of string, and may apply further logic as follows:
for (int i=0; i< taxNumber.Length; i++)
{
if (Char.IsDigit(taxNumber[i]))
{
if(taxNumber[i-1]==taxNumber[i])
{
/*Further assign values*/
}
}
Try this Code
string taxNumber = "1222233333445";
char[] aa = taxNumber.ToCharArray();
List<string> finals = new List<string>();
string temp = string.Empty;
for (int i = 0; i < aa.Length; i++)
{
if (i == 0)
{
temp = aa[i].ToString();
}
else
{
if (aa[i].ToString() == aa[i - 1].ToString())
{
temp += aa[i];
}
else
{
if (temp != string.Empty)
{
finals.Add(temp);
temp = aa[i].ToString();
}
}
if (i == aa.Length - 1)
{
if (aa[i].ToString() != aa[i - 1].ToString())
{
temp = aa[i].ToString();
finals.Add(temp);
}
else
{
finals.Add(temp);
}
}
}
}
and check value of finals string list
you may use regex:
string strRegex = #"(1+|2+|3+|4+|5+|6+|7+|8+|9+|0+)";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = #"1222233333445";
return myRegex.Split(strTargetString);

Splitting a string array

I have a string array string[] arr, which contains values like N36102W114383, N36102W114382 etc...
I want to split the each and every string such that the value comes like this N36082 and W115080.
What is the best way to do this?
This should work for you.
Regex regexObj = new Regex(#"\w\d+"); # matches a character followed by a sequence of digits
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
matchResults = matchResults.NextMatch(); #two mathches N36102 and W114383
}
If you have the fixed format every time you can just do this:
string[] split_data = data_string.Insert(data_string.IndexOf("W"), ",")
.Split(",", StringSplitOptions.None);
Here you insert a recognizable delimiter into your string and then split it by this delimiter.
Forgive me if this doesn't quite compile, but I'd just break down and write the string processing function by hand:
public static IEnumerable<string> Split(string str)
{
char [] chars = str.ToCharArray();
int last = 0;
for(int i = 1; i < chars.Length; i++) {
if(char.IsLetter(chars[i])) {
yield return new string(chars, last, i - last);
last = i;
}
}
yield return new string(chars, last, chars.Length - last);
}
If you use C#, please try:
String[] code = new Regex("(?:([A-Z][0-9]+))").Split(text).Where(e => e.Length > 0 && e != ",").ToArray();
in case you're only looking for the format NxxxxxWxxxxx, this will do just fine :
Regex r = new Regex(#"(N[0-9]+)(W[0-9]+)");
Match mc = r.Match(arr[i]);
string N = mc.Groups[1];
string W = mc.Groups[2];
Using the 'Split' and 'IsLetter' string functions, this is relatively easy in c#.
Don't forget to write unit tests - the following may have some corner case errors!
// input has form "N36102W114383, N36102W114382"
// output: "N36102", "W114383", "N36102", "W114382", ...
string[] ParseSequenceString(string input)
{
string[] inputStrings = string.Split(',');
List<string> outputStrings = new List<string>();
foreach (string value in inputstrings) {
List<string> valuesInString = ParseValuesInString(value);
outputStrings.Add(valuesInString);
}
return outputStrings.ToArray();
}
// input has form "N36102W114383"
// output: "N36102", "W114383"
List<string> ParseValuesInString(string inputString)
{
List<string> outputValues = new List<string>();
string currentValue = string.Empty;
foreach (char c in inputString)
{
if (char.IsLetter(c))
{
if (currentValue .Length == 0)
{
currentValue += c;
} else
{
outputValues.Add(currentValue);
currentValue = string.Empty;
}
}
currentValue += c;
}
outputValues.Add(currentValue);
return outputValues;
}

formatting string in MVC /C#

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?
Thanks.
By using regex:
public static string FormatTest1(string num)
{
string formatPattern = #"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
}
// test
string test = FormatTest1("731478718861993983");
// test result: 73-1478-7188-6199-3983
If you're dealing with a long number, you can use a NumberFormatInfo to format it:
First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Next, you can use it on your numbers:
long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
After all, .Net has very good globalization support - you're better served using it!
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
LINQ-only one-liner:
var str = "731478718861993983";
var result =
new string(
str.ToCharArray().
Reverse(). // So that it will go over string right-to-left
Select((c, i) => new { #char = c, group = i / 4}). // Keep group number
Reverse(). // Restore original order
GroupBy(t => t.group). // Now do the actual grouping
Aggregate("", (s, grouping) => "-" + new string(
grouping.
Select(gr => gr.#char).
ToArray())).
ToArray()).
Trim('-');
This can handle strings of arbitrary lenghs.
Simple (and naive) extension method :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("731478718861993983".InsertChar("-", 4));
}
}
static class Ext
{
public static string InsertChar(this string str, string c, int i)
{
for (int j = str.Length - i; j >= 0; j -= i)
{
str = str.Insert(j, c);
}
return str;
}
}
If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:
string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);
Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be #"\B\d{4}".
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");
My first thought is:
String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");
(don't remember if index is zero-based, in which case you should use my values -1)
but there is probably some easier way to do this...
If the position of "-" is always the same then you can try
string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-");
Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.
string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
Edit: amended code, since you said they were held as a string in your your original question

How to remove characters from a string using LINQ

I'm having a String like
XQ74MNT8244A
i nee to remove all the char from the string.
so the output will be like
748244
How to do this?
Please help me to do this
new string("XQ74MNT8244A".Where(char.IsDigit).ToArray()) == "748244"
Two options. Using Linq on .Net 4 (on 3.5 it is similar - it doesn't have that many overloads of all methods):
string s1 = String.Concat(str.Where(Char.IsDigit));
Or, using a regular expression:
string s2 = Regex.Replace(str, #"\D+", "");
I should add that IsDigit and \D are Unicode-aware, so it accepts quite a few digits besides 0-9, for example "542abc٣٤".
You can easily adapt them to a check between 0 and 9, or to [^0-9]+.
string value = "HTQ7899HBVxzzxx";
Console.WriteLine(new string(
value.Where(x => (x >= '0' && x <= '9'))
.ToArray()));
If you need only digits and you really want Linq try this:
youstring.ToCharArray().Where(x => char.IsDigit(x)).ToArray();
Using LINQ:
public string FilterString(string input)
{
return new string(input.Where(char.IsNumber).ToArray());
}
Something like this?
"XQ74MNT8244A".ToCharArray().Where(x => { var i = 0; return Int32.TryParse(x.ToString(), out i); })
string s = "XQ74MNT8244A";
var x = new string(s.Where(c => (c >= '0' && c <= '9')).ToArray());
How about an extension method (and overload) that does this for you:
public static string NumbersOnly(this string Instring)
{
return Instring.NumbersOnly("");
}
public static string NumbersOnly(this string Instring, string AlsoAllowed)
{
char[] aChar = Instring.ToCharArray();
int intCount = 0;
string strTemp = "";
for (intCount = 0; intCount <= Instring.Length - 1; intCount++)
{
if (char.IsNumber(aChar[intCount]) || AlsoAllowed.IndexOf(aChar[intCount]) > -1)
{
strTemp = strTemp + aChar[intCount];
}
}
return strTemp;
}
The overload is so you can retain "-", "$" or "." as well, if you wish (instead of strictly numbers).
Usage:
string numsOnly = "XQ74MNT8244A".NumbersOnly();

Categories