string multiple string value in one int variable - c#

how to store multiple string value in one int variable
string OutReader = ConfigurationManager.AppSettings["OutReader"].ToString();
int outrdr = Convert.ToInt32(OutReader);
The value of AppSettings["OutReader"] is: "(1,2)"

If AppSettings["OutReader"] currently have in it a string like: "(1,2)"
then you can do:
var sections = ConfigurationManager.AppSettings["OutReader"].Replace("(",string.Empty)
.Replace(")",string.Empty)
.Split(',');
if(sections.Length > 0)
{
int outrdr = Convert.ToInt32(sections[0]);
}
This can still throw an exception in the case that section[0] can't be parsed into an int so use .TryParse instead - Just wanted to stay as close to the question as possible

Related

error "Cannot implicitly convert 'string' to 'int' [duplicate]

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database.
How can I do this?
Try this:
int x = Int32.Parse(TextBoxD1.Text);
or better yet:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
If you are curious, the difference between Parse and TryParse is best summed up like this:
The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN
Convert.ToInt32( TextBoxD1.Text );
Use this if you feel confident that the contents of the text box is a valid int. A safer option is
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
This will provide you with some default value you can use. Int32.TryParse also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if statement.
if( Int32.TryParse( TextBoxD1.Text, out val ){
DoSomething(..);
} else {
HandleBadInput(..);
}
int.TryParse()
It won't throw if the text is not numeric.
int myInt = int.Parse(TextBoxD1.Text)
Another way would be:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
The difference between the two is that the first one would throw an exception if the value in your textbox can't be converted, whereas the second one would just return false.
Be careful when using Convert.ToInt32() on a char!
It will return the UTF-16 code of the character!
If you access the string only in a certain position using the [i] indexing operator, it will return a char and not a string!
String input = "123678";
^
|
int indexOfSeven = 4;
int x = Convert.ToInt32(input[indexOfSeven]); // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString()); // Returns 7
You need to parse the string, and you also need to ensure that it is truly in the format of an integer.
The easiest way is this:
int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}
int x = 0;
int.TryParse(TextBoxD1.Text, out x);
The TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.
See Int32.TryParse Method (String, Int32) for more detailed information.
Enjoy it...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
While there are already many solutions here that describe int.Parse, there's something important missing in all the answers. Typically, the string representations of numeric values differ by culture. Elements of numeric strings such as currency symbols, group (or thousands) separators, and decimal separators all vary by culture.
If you want to create a robust way to parse a string to an integer, it's therefore important to take the culture information into account. If you don't, the current culture settings will be used. That might give a user a pretty nasty surprise -- or even worse, if you're parsing file formats. If you just want English parsing, it's best to simply make it explicit, by specifying the culture settings to use:
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
// use result...
}
For more information, read up on CultureInfo, specifically NumberFormatInfo on MSDN.
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
You can write your own extension method
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
And wherever in code just call
int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null
In this concrete case
int yourValue = TextBoxD1.Text.ParseInt();
As explained in the TryParse documentation, TryParse() returns a Boolean which indicates that a valid number was found:
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// Put val in database
}
else
{
// Handle the case that the string doesn't contain a valid number
}
You can convert string to int many different type methods in C#
First one is mostly use :
string test = "123";
int x = Convert.ToInt16(test);
if int value is higher you should use int32 type.
Second one:
int x = int.Parse(text);
if you want to error check, you can use TryParse method. In below I add nullable type;
int i=0;
Int32.TryParse(text, out i) ? i : (int?)null);
Enjoy your codes....
Conversion of string to int can be done for: int, Int32, Int64 and other data types reflecting integer data types in .NET
Below example shows this conversion:
This shows (for info) data adapter element initialized to int value. The same can be done directly like,
int xxiiqVal = Int32.Parse(strNabcd);
Ex.
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["#Nii"].Value = Int32.Parse(strNii );
Link to see this demo.
int i = Convert.ToInt32(TextBoxD1.Text);
//May be quite some time ago but I just want throw in some line for any one who may still need it
int intValue;
string strValue = "2021";
try
{
intValue = Convert.ToInt32(strValue);
}
catch
{
//Default Value if conversion fails OR return specified error
// Example
intValue = 2000;
}
You can use either,
int i = Convert.ToInt32(TextBoxD1.Text);
or
int i = int.Parse(TextBoxD1.Text);
You can do like below without TryParse or inbuilt functions:
static int convertToInt(string a)
{
int x = 0;
for (int i = 0; i < a.Length; i++)
{
int temp = a[i] - '0';
if (temp != 0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x;
}
You also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).
public static class StringExtensions
{
/// <summary>
/// Converts a string to int.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The converted integer.</returns>
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Checks whether the value is integer.
/// </summary>
/// <param name="value">The string to check.</param>
/// <param name="result">The out int parameter.</param>
/// <returns>true if the value is an integer; otherwise, false.</returns>
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
And then you can call it that way:
If you are sure that your string is an integer, like "50".
int num = TextBoxD1.Text.ParseToInt32();
If you are not sure and want to prevent crashes.
int num;
if (TextBoxD1.Text.TryParseToInt32(out num))
{
//The parse was successful, the num has the parsed value.
}
To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.
You can convert a string to int in C# using:
Functions of convert class i.e. Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() or by using Parse and TryParse Functions. Examples are given here.
This would do
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
Or you can use
int xi = Int32.Parse(x);
Refer Microsoft Developer Network for more information
You can convert string to an integer value with the help of parse method.
Eg:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
In C# v.7 you could use an inline out parameter, without an additional variable declaration:
int.TryParse(TextBoxD1.Text, out int x);
The way I always do this is like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example_string_to_int
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
// This turns the text in text box 1 into a string
int b;
if (!int.TryParse(a, out b))
{
MessageBox.Show("This is not a number");
}
else
{
textBox2.Text = a+" is a number" ;
}
// Then this 'if' statement says if the string is not a number, display an error, else now you will have an integer.
}
}
}
This is how I would do it.
All the above answers are good but for information, we can use int.TryParse which is safe to convert string to int, for example
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.
Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)
In case you know the string is an integer do:
int value = int.Parse(TextBoxD1.Text);
In case you don't know the string is an integer do it safely with TryParse.
In C# 7.0 you can use inline variable declaration.
If parse successes - value = its parsed value.
If parse fails - value = 0.
Code:
if (int.TryParse(TextBoxD1.Text, out int value))
{
// Parse succeed
}
Drawback:
You cannot differentiate between a 0 value and a non parsed value.
Here is the version of doing it via an Extension Method that has an option to set the default value as well, if the converting fails. In fact, this is what I used to convert a string input to any convertible type:
using System;
using System.ComponentModel;
public static class StringExtensions
{
public static TOutput AsOrDefault<TOutput>(this string input, TOutput defaultValue = default)
where TOutput : IConvertible
{
TOutput output = defaultValue;
try
{
var converter = TypeDescriptor.GetConverter(typeof(TOutput));
if (converter != null)
{
output = (TOutput)converter.ConvertFromString(input);
}
}
catch { }
return output;
}
}
For my usage, I limited the output to be one of the convertible types: https://learn.microsoft.com/en-us/dotnet/api/system.iconvertible?view=net-5.0. I don't need crazy logics to convert a string to a class, for example.
To use it to convert a string to int:
using FluentAssertions;
using Xunit;
[Theory]
[InlineData("0", 0)]
[InlineData("1", 1)]
[InlineData("123", 123)]
[InlineData("-123", -123)]
public void ValidStringWithNoDefaultValue_ReturnsExpectedResult(string input, int expectedResult)
{
var result = input.AsOrDefault<int>();
result.Should().Be(expectedResult);
}
[Theory]
[InlineData("0", 999, 0)]
[InlineData("1", 999, 1)]
[InlineData("123", 999, 123)]
[InlineData("-123", -999, -123)]
public void ValidStringWithDefaultValue_ReturnsExpectedResult(string input, int defaultValue, int expectedResult)
{
var result = input.AsOrDefault(defaultValue);
result.Should().Be(expectedResult);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("abc")]
public void InvalidStringWithNoDefaultValue_ReturnsIntegerDefault(string input)
{
var result = input.AsOrDefault<int>();
result.Should().Be(default(int));
}
[Theory]
[InlineData("", 0)]
[InlineData(" ", 1)]
[InlineData("abc", 234)]
public void InvalidStringWithDefaultValue_ReturnsDefaultValue(string input, int defaultValue)
{
var result = input.AsOrDefault(defaultValue);
result.Should().Be(defaultValue);
}
METHOD 1
int TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
Console.WriteLine("String not Convertable to an Integer");
}
METHOD 2
int TheAnswer2 = 0;
try {
TheAnswer2 = Int32.Parse("42");
}
catch {
Console.WriteLine("String not Convertable to an Integer");
}
METHOD 3
int TheAnswer3 = 0;
try {
TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
Console.WriteLine("String is null");
}
catch (OverflowException) {
Console.WriteLine("String represents a number less than"
+ "MinValue or greater than MaxValue");
}
You can try the following. It will work:
int x = Convert.ToInt32(TextBoxD1.Text);
The string value in the variable TextBoxD1.Text will be converted into Int32 and will be stored in x.
While I agree on using the TryParse method, a lot of people dislike the use of out parameter (myself included). With tuple support having been added to C#, an alternative is to create an extension method that will limit the number of times you use out to a single instance:
public static class StringExtensions
{
public static (int result, bool canParse) TryParse(this string s)
{
int res;
var valid = int.TryParse(s, out res);
return (result: res, canParse: valid);
}
}
(Source: C# how to convert a string to int)

Print hexadecimal code from int into string

I need to save a string with the hexadecimal code of an int.
For example the hexadecimal value for the int 15 is xoooF.
My problem is that I have to save this code in a string like this:
int myint = myStringLength; //this value might change
string myIntExhCode = myint.convertThisIntoMyCode();
//and the string has to be exactly "/xoooF"
So in this question I have two problmes:
The first is how to automatically convert an int into the hexadecimal code like 15 = xoooF
The second is how to create a string containing \xoooF because any try of concatenating strings like this resulted into a \\xoooF and this is not correct since in output I need the string to be converted into the ascii code.
How can I achieve those two tasks?
Any help will be appreciated
Your question is quite vague. If you want hexadecimal format, but with 0 (digit zero) changed into o (small latin letter o) you can implement, say, an extension method (in order to keep your proposed code intact):
public static partial class IntExtensions {
public static string convertThisIntoMyCode(this int value) {
return "\\x" + value.ToString("X4").Replace('0', 'o'); // or "/x" + ...
}
}
...
int myint = myStringLength; //this value might change
string myIntExhCode = myint.convertThisIntoMyCode();
// Test output
Console.Write(myIntExhCode);
How about
int i = 15;
string result = "\\x" + i.ToString("X").PadLeft(4, 'o');

Having trouble converting string to int

In my program I have a treeView. In the section that I am working with, the node's displayNames are numerical integer values, but are displayed as strings. I have come to a point in my program where I need to convert and temporarily store these displayNames in an integer variable. I usually use Regex.Match() to do this with no problem, but in this scenario I am getting the compiler error: Cannot implicitly convert type 'string' to 'int'.
This is my code:
//This is the parent node as you may be able to see below
//The children of this node have DisplayNames that are integers
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');
//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
for (int i = 0; i < node.Children.Count(); i++)
{
//Error on this line!!**
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
}
}
*NOTE: DisplayName.Value is a string
To get from string to int, use int.Parse(string), it returns the int represented by the passed string and throws if the input format is incorrect.
int.Parse(node.Children.ElementAt(i).DisplayName.Value)
You can also use int.TryParse if you don't want the throw. in that case you would use:
int parsedValue;
if (int.TryParse(node.Children.ElementAt(i).DisplayName.Value, out parsedValue))
{
///Do whatever with the int
}
The problem is becuase you're casting from Match to int in this call
IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
Try something like this:
Match m = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, #"\d+").Value;
int value = m.Matches[0] //You'll have to verify this line, I'm going from memory here.

Modifying values within a list

I've been trying to write a program which can scan a raw data file and normalize it for data mining processes, I've trying to read the data from the file and store it in a list this way:
public static List<Normalize> NF()
{
//Regex r = new Regex(#"^\d+$");
List<Normalize> N = new List<Normalize>();
StreamReader ss = new StreamReader(#"C:\Users\User\Desktop\NN.txt");
String Line = null;
while (!ss.EndOfStream) {
Line = ss.ReadLine();
var L = Line.Split(',').ToList();
N.Add(new Normalize { age = Convert.ToInt16(L[0]),
Sex = L[1],
T3 = Convert.ToDouble(L[2]),
TT4 = Convert.ToDouble(L[3]),
TFU = Convert.ToDouble(L[4]),
FTI = Convert.ToDouble(L[5]),
RC = L[6],
R = L[7]
});
}
return N;
}
}
struct Normalize {
public int age;
public String Sex;
public double T3;
public double TT4;
public double TFU;
public double FTI;
public String RC;
public String R;
}
At this moment I want to go through the list that I've made and categorize the data , similar to this :
var X= NF();
for (int i = 0; i < X.Count; i++) {
if (X[i].age > 0 && X[i].age <= 5) { // Change the X[i].age value to 1 }
else if (X[i].age > 5 && X[i].age <= 10) { // Change the X[i].age value to 2 }
...
}
But the compiler says X[i].[variable name] is not a variable and cannot be modified in this way. My question is, what would be an efficient way to perform this operation.
struct Normalize is a value type, not a reference type, therefore you cannot change its fields like that. Change it to class Normalize
Change struct Normalize to class Normalize and iterate with foreach loop. It's way cleaner.
You could also set variables to private and use getters/setters to check/set variable.
foreach (Normalize x in X)
{
if (x.getAge() > 0 && x.getAge() <= 5)
x.setAge(1)
...
}
Edit:
just saw you already got your answer
Modifying struct field is fine as long as it's a single entity (Given its a mutable struct). This is possible -
var obj = new Normalize();
obh.Age = 10;
But in your case you are accessing the struct using indexer from the list.
Indexer will return copy of your struct and modifying the value won't reflect it back to the list which ain't you want.
Hence compiler is throwing error to stop you from writing this out.
As Alex mentioned, you should go for creating class instead of struct if you want to modify it.
On a side note, its always advisable to have immutable structs instead of mutable structs.

converting int var to string var with unassigned local variable error

I am trying to convert an int var to a string var for use in a .txt file. i am coming up with a "unassigned local variable error". I have looked thru other questions but i don't see what i am missing. I have been able to convert int var to a string var before, i am not really sure where i am going wrong. If you could also give me the theory with the solution it would be most helpfull
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
if (BTSBtn.Checked)
{
sbntmsk = 30;
}
string subntmsk;
subntmsk = sbntmsk.ToString();
The compiler has no way to know if your checkboxes will be checked at runtime and so it complains because there is a possibility that the variable sbntmsk reaches the point where you try to convert it to a string without having a value assigned.
To fix the message declare and initialize sbntmsk with (or whatever default value you like)
int sbntmsk = 0;
You need to provide a default value for the integer. For example, what would you expect to be in the string if neither button was checked?
You could just use strings?
var sbntmsk = String.Empty;
if (RBSBtn.Checked)
{
sbntmsk = "29";
}
if (BTSBtn.Checked)
{
sbntmsk = "30";
}
Try using this approach:
int sbntmsk;
if (RBSBtn.Checked)
{
sbntmsk = 29;
}
else if (BTSBtn.Checked) // Notice the ELSE - IF
{
sbntmsk = 30;
}
else
{
sbntmsk = 0; // a default value
}
string subntmsk = String.Empty; // initialize with empty
subntmsk = sbntmsk.ToString();
Since using multiple checkboxes you are assigning to a same variable so no need to check all IF blocks. Also, using this way you have a possibility to define an 'ELSE' block at the end.
Hope it helps!

Categories

Resources