How to convert a string with comma to integer in C# - 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 ;
}

Related

Split a string and convert one of the index as int

I have the following code:
static void Main(string[] args)
{
string prueba = "Something_2.zip";
int num;
prueba = prueba.Split('.')[0];
if (!prueba.Contains("_"))
{
prueba = prueba + "_";
}
else
{
//The code I want to try
}
}
The idea is that in the else I want to split the string after the _ and convert it to int, I did this like
num = Convert.ToInt16(prueba.Split('_')[1]);
but can I cast the split? for example num = (int)(prueba.Split('_')[1]);
Is it possible to do it that way? Or I have to use the Convert?
You Cannot cast string as integer, so you need to do some conversion:
I suggest you to use Int.TryParse() in this scenario.
Hence the else part will be like the following:
else
{
if(int.TryParse(prueba.Substring(prueba.LastIndexOf('_')),out num))
{
//proceed your code
}
else
{
//Throw error message
}
}
Convert the string to int like this:
var myInt = 0;
if (Int32.TryParse(prueba.Split('_')[1], out myInt))
{
// use myInt here
}
It's a string, so you'll have to parse it. You can use Convert.ToInt32, int.Parse, or int.TryParse to do so, like so:
var numString = prueba.Split('_')[1];
var numByConvert = Convert.ToInt32(numString);
var numByParse = int.Parse(numString);
int numByTryParse;
if(int.TryParse(numString, out numByTryParse))
{/*Success, numByTryParse is populated with the numString's int value.*/}
else
{/*Failure. You can handle the fact that it failed to parse now. numByTryParse will be 0 */}
string prueba = "Something_2.zip";
prueba = prueba.Split('.')[0];
int theValue = 0; // Also default value if no '_' is found
var index = prueba.LastIndexOf('_');
if(index >= 0)
int.TryParse(prueba.Substring(index + 1), out theValue);
theValue.Dump();
You could use a regular expression and avoid all the string splitting logic. If you need an explanation of the regex I've used see https://regex101.com/r/fW9fX5/1
var num = -1; // set to default value that you intend to use when the string doesn't contain an underscore
var fileNamePattern = new Regex(#".*_(?<num>\d+)\..*");
var regexMatch = fileNamePattern.Match("Something_2.zip");
if (regexMatch.Success)
{
int.TryParse(regexMatch.Groups["num"].Value, out num);
}

Get String (Text) before next upper letter

I have the following:
string test = "CustomerNumber";
or
string test2 = "CustomerNumberHello";
the result should be:
string result = "Customer";
The first word from the string is the result, the first word goes until the first uppercase letter, here 'N'
I already tried some things like this:
var result = string.Concat(s.Select(c => char.IsUpper(c) ? " " + c.ToString() : c.ToString()))
.TrimStart();
But without success, hope someone could offer me a small and clean solution (without RegEx).
The following should work:
var result = new string(
test.TakeWhile((c, index) => index == 0 || char.IsLower(c)).ToArray());
You could just go through the string to see which values (ASCII) are below 97 and remove the end. Not the prettiest or LINQiest way, but it works...
string test2 = "CustomerNumberHello";
for (int i = 1; i < test2.Length; i++)
{
if (test2[i] < 97)
{
test2 = test2.Remove(i, test2.Length - i);
break;
}
}
Console.WriteLine(test2); // Prints Customer
Try this
private static string GetFirstWord(string source)
{
return source.Substring(0, source.IndexOfAny("ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToArray(), 1));
}
Z][a-z]+ regex it will split the string to string that start with big letters her is an example
regex = "[A-Z][a-z]+";
MatchCollection mc = Regex.Matches(richTextBox1.Text, regex);
foreach (Match match in mc)
if (!match.ToString().Equals(""))
Console.writln(match.ToString() + "\n");
I have tested, this works:
string cust = "CustomerNumberHello";
string[] str = System.Text.RegularExpressions.Regex.Split(cust, #"[a-z]+");
string str2 = cust.Remove(cust.IndexOf(str[1], 1));

how do i convert string numbers to int

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.

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();

Strip prefix and value

if I have the string "freq1" or "freq12" and so on, how can I strip out freq and also the number by itself?
string foo = "freq12";
string fooPart = foo.Substring(4); // "12"
int fooNumber = int.parse(fooPart); // 12
if the "freq" part is not constant, then you can use regular expressions:
using System.Text.RegularExpressions;
string pattern = #"([A-Za-z]+)(\d+)";
string foo = "freq12";
Match match = Regex.Match(foo, pattern);
string fooPart = match.Groups[1].Value;
int fooNumber = int.Parse(match.Groups[2].Value);
Is it always going to be the text freq that prepends the number within the string? If so, your solution is very simple:
var str = "freq12";
var num = int.Parse(str.Substring(4));
Edit: Here's a more generic method in the case that the first part of the string isn't always "freq".
var str = "freq12";
int splitIndex;
for(splitIndex = 0; splitIndex < str.Length; splitIndex++)
{
if (char.IsNumeric(str[splitIndex]))
break;
}
if (splitIndex == str.Length)
throw new InvalidOperationException("The input string does not contain a numeric part.");
var textPart = int.Parse(str.Substring(0, splitIndex));
var numPart = int.Parse(str.Substring(splitIndex));
In the given example, textPart should evaluate to freq and numPart to 12. Let me know if this still isn't what you want.
Try something like this:
String oldString = "freq1";
String newString = oldString.Replace("freq", String.Empty);
If you know that the word "freq" will always be there, then you can do something like:
string number = "freq1".Replace("freq","");
That will result in "1".

Categories