This question already has answers here:
Adding numbers to a string?
(5 answers)
Closed 7 years ago.
i am looping through some nodes and getting the charge and adding them together. the charge is of type string though.
first time it loops string charge = "309",
second time it loop string charge = "38";
`Looping through list of nodes
{
saBillDetail.TotalServiceUsage += totalSvcNode.InnerText;
}
`
I would have expected that I could add them together, but they are being concatenated instead like this:
`charge + charge = '30938'`
How can I force these strings to be treated as numbers? and get output like this at the end of the loop
`charge + charge = '347'`
As people allready answered this maybe another solution
So you don't get errors
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return iOne + iTwo;
}
Or if you want a string result.
private static String AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return (iOne + iTwo).ToString();
}
EDIT:
As Alexei Levenkov stated you could/should handle exceptions.
Maybe something like this will help you during development
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
bool successParseOne = Int32.TryParse(one, out iOne);
bool successParseTwo = Int32.TryParse(two, out iTwo);
if (!successParseOne)
{
throw new ArgumentException("one");
}
else if(!successParseTwo)
{
throw new ArgumentException("two");
}
return (iOne + iTwo);
}
So when you have a wrong number you will be notified if you use try/catch
You need to parse the numbers from the strings:
string number1 = "309";
string number2 = "38";
int result = int.Parse(number1) + int.Parse(number2);
Then you can set the text equal to that string representation:
string addResult = result.ToString();
Note: Int32.Parse() will throw an exception if the format isn't correct. Consider using Int32.TryParse() for a bool way to capture an impossible parsing.
You will need to convert your strings to integer, add them and convert the result back to string:
int sum = 0;
foreach (string strNumber in strNumberCollection)
{
int number;
if (int.TryParse(strNumber, out number))
sum += number;
}
string total = sum.ToString();
Related
This question already has answers here:
How could I convert data from string to long in c#
(8 answers)
Closed last year.
The line of code with the issue:
memory.WriteFloat(tp_x, this.X)
this.X is fine and works with no issues.
For the value tp_x, it is a STRING.
I am taking this from a text file and parsing it to an exact value. I have tried several times to convert this string to Int32/64, float, long, etc. But the memory.WriteFloat() is not taking it without an error.
Picture of code
I have tried to use
memory.ReadFloat(tp_X)
But I get the same error.
Cannot convert from 'string' to 'long'. I have tried so much different codes to convert it and use it, but nothing has worked or changed so I am asking a question here. I wouldn't be asking if I had no idea. Thank you, please let me know!
EDITED for pm100
Here is my new code:
Picture 1
Where I get my error Picture 2
So using your code #pm100 as seen in the pictures, I get no problems and I can compile perfectly. Although, when I execute this I get error
I get the error System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt64(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Int64.Parse(String s)
My code:
int counter = 0;
// location is the selected index of the combobox that the user selected
foreach (string line in System.IO.File.ReadLines(#"path"))
{
if (counter == location)
{
string[] words = line.Split(",");
int tempcounter = 1;
string tp_x = "";
string tp_y = "";
string tp_z = "";
foreach (var word in words)
{
if (tempcounter == 1)
{
tp_x += word;
}
if (tempcounter == 2)
{
tp_y += word;
}
if (tempcounter == 3)
{
tp_z += word;
}
tempcounter += 1;
//everytime works perfect above, now below
long l = System.Int64.Parse(tp_x);
long l2 = System.Int64.Parse(tp_y);
long l3 = System.Int64.Parse(tp_z);
tp_xx = l;
tp_yy = l2;
tp_zz = l3;
for (int i = 0; i < address.vz.Length; i++)
{
mem.WriteFloat(tp_xx, this.X);
mem.WriteFloat(tp_yy, this.Y);
mem.WriteFloat(tp_zz, this.Z);
}
}
return false;
}
counter += 1;
}
You need Int64.Parse
string s="1234";
long l = System.Int64.Parse(s);
Or if you are not sure that the string contains a valid number use
bool success = Int64.TryParse(s, out long l);
This question already has answers here:
Reading an integer from user input
(14 answers)
How can I convert String to Int?
(31 answers)
Closed 5 years ago.
I have created some classes and in one instance, I want the programme to read the answer (numeric). I have tried to set the class as string and as int but continue to have problems. Please bear with me I am just starting to learn programming.
public **int** Age { get; set; }
Animal cuddle = new Animal();
cuddle.Color = "";
cuddle.Age = 0;
cuddle.Name = "";
cuddle.Type = "";
Console.WriteLine("Hi, {0} How old do you want your {1,2} to be?\n Remember, if your {3} is older then 5 you will have to give her double!!!", name, cuddle.Color, player);
cuddle.Age = **Console.ReadLine**();
if (cuddle.Age < 5)
{
In this instance it doesn't accept the Console.ReadLine.
If I change the int to string as:
public **string** Age { get; set; }
then it doesn't accept
if (**cuddle.Age < 5**)
I have tried without the brackets and/or with (**cuddle.Age = < 5**)
int age = 0;
if(int.TryParse(Console.ReadLine(), out age)) //It can be parsed as integer:
{
if(age < 5)
{
// do your work
}
}
You can go further more and repeat reading line while the input is not parse-able:
int age = 0;
while(!int.TryParse(Console.ReadLine(), out age));
if(age < 5)
{
// do your work
}
Here is the DEMO
You can cast to an int, on user input:
int theInt = Convert.ToInt32(Console.ReadLine());
This is possibly a duplicate of this question: Reading an integer from user input
So i have a question. I'm trying do make a function witch returns a number, but the problem is that i can't convert int to string. My functions looks like this:
static string EnemyDmg(EnemyDmg _dmg)
{
string result = "";
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
result = EnemyDmg;
return result;
}
but it should do this
int EnemyDmg
= CharAttack - EnemyDefense;
if (EnemyDmg < 1)
EnemyDmg = 4;
Console.WriteLine(EnemyName + " takes " + EnemyDmg + " Damage");
has anyone an idea?
PS: The 4 is just a random number.
should be static int EnemyDmg(EnemyDmg _dmg). You should return an int, and convert to string outside the function iif you need that
Anyway, to convert a String s into an int i:
int i = Int32.Parse(s);
to convert an int i into a string s
string s = i.ToString();
string s = ""+i; // more "java-like"
This question is a bit ambiguous; I'm not sure why you've done it this way.
You can convert a C# integer to a string with the .ToString() method, like this:
int a = 12;
string aString = a.ToString();
Console.WriteLine(a);
https://dotnetfiddle.net/sMC3hU
static string toStr(int intInput)
{
string str = intInput.ToString();
return str;
}
}
This code will do it for you. There is no need to use if statement as there is no any specific requirement, it will make more complicated code.
or else
you can direct use ToString parameter if there is an user input just refer to the 3rd line.
This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 9 years ago.
static void Main(string[] args)
{
string foo = "jason123x40";
char[] foo2 = foo.ToCharArray();
string foo3 = "";
for (int i = 0; i < foo2.Length; i++)
{
int num = 0;
Int32.TryParse(foo2[i].ToString(), out num);
if (num != 0)
{
foo3 += num.ToString();
}
}
Console.WriteLine(foo3);
Console.ReadLine();
}
So lets say I have a string called "john10smith250". The result should be "10250". However I would get "125" instead with my code.
The reason I filtered out the 0 was because I didn't want any non numeric characters to be treated as a zero.
Is there a better way to convert a part of a string into an int?
Using LINQ :
var myString = "john10smith250";
var myNumbers = myString.Where(x => char.IsDigit(x)).ToArray();
var myNewString = new String(myNumbers);
You've got a couple of good solutions that change the approach and shorten your code. For completeness, here is how you make your code work.
Your code assumes that if the num is zero, the parse has failed:
int num = 0;
Int32.TryParse(foo2[i].ToString(), out num);
if (num != 0) // This is wrong
{
foo3 += num.ToString();
}
You need to change the code like this:
int num = 0;
if (Int32.TryParse(foo2[i].ToString(), out num))
{
foo3 += num.ToString();
}
The reason your code did not work was that you ignored the return value of TryParse. It returns false if the parse fails, or true if the parse succeeds, even if the number being parsed is zero. In fact, that's the reason behind TryParse taking an out parameter (as opposed to returning the value directly, the way the Int32.Parse does).
You can solve it by using Regx
\d+ is the regex for an integer number.
So
string outputstring = Regex.Match(yourstring, #"\d+").Value;
will give you that number as a string. Int32.Parse(outputstring) will then give you the number.
or you can do like this
go through the string and use Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
{
val = int.Parse(b);
}
use :
var str= "jason123x40";
var number= str.Where(x => char.IsDigit(x)).Select(x => x);
Pretty close to what you have there...
int parseNumbersFromString(string data)
{
string number = "";
for(int i = 0; i < data.Length; ++i)
{
if(char.IsDigit(data[i]))
number += data[i];
}
return Convert.ToInt32(number);
}
*You can use index to access a char in a string
*IsDigit check if this char is a digit then append it to the string foo2 if condition is true
string foo = "jason0123x40";
string foo2 = "";
for (int i = 0; i < foo.Length; i++)
{
if (char.IsDigit(foo[i]))
foo2 += foo[i];
}
Console.WriteLine(foo2);
Console.ReadLine();
You can use a regular expression as follows:
string foo = "jason123x40";
string foo3 = Regex.Replace(foo, #"\D", "");
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Can I "multiply" a string (in C#)?
In Python I can do this:
>>> i = 3
>>> 'hello' * i
'hellohellohello'
How can I multiply strings in C# similarly to in Python? I could easily do it in a for loop but that gets tedious and non-expressive.
Ultimately I'm writing out to console recursively with an indented level being incremented with each call.
parent
child
child
child
grandchild
And it'd be easiest to just do "\t" * indent.
There is an extension method for it in this post.
public static string Multiply(this string source, int multiplier)
{
StringBuilder sb = new StringBuilder(multiplier * source.Length);
for (int i = 0; i < multiplier; i++)
{
sb.Append(source);
}
return sb.ToString();
}
string s = "</li></ul>".Multiply(10);
If you just need a single character you can do:
new string('\t', i)
See this post for more info.
Here's how I do it...
string value = new string(' ',5).Replace(" ","Apple");
There's nothing built-in to the BCL to do this, but a bit of LINQ can accomplish the task easily enough:
var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());
int indent = 5;
string s = new string('\t', indent);
One way of doing this is the following - but it's not that nice.
String.Join(String.Empty, Enumerable.Repeat("hello", 3).ToArray())
UPDATE
Ahhhh ... I remeber ... for chars ...
new String('x', 3)
how about with a linq aggregate...
var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);
There is no such statement in C#; your best bet is probably your own MultiplyString() function.
Per mmyers:
public static string times(this string str, int count)
{
StringBuilder sb = new StringBuilder();
for(int i=0; i<count; i++)
{
sb.Append(str);
}
return sb.ToString();
}
As long as it's only one character that you want to repeat, there is a String constructor that you can use:
string indentation = new String('\t', indent);
I don't think that you can extend System.String with an operator overload, but you could make a string wrapper class to do it.
public class StringWrapper
{
public string Value { get; set; }
public StringWrapper()
{
this.Value = string.Empty;
}
public StringWrapper(string value)
{
this.Value = value;
}
public static StringWrapper operator *(StringWrapper wrapper,
int timesToRepeat)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < timesToRepeat; i++)
{
builder.Append(wrapper.Value);
}
return new StringWrapper(builder.ToString());
}
}
Then call it like...
var helloTimesThree = new StringWrapper("hello") * 3;
And get the value from...
helloTimesThree.Value;
Of course, the sane thing to do would be to have your function track and pass in the current depth and dump tabs out in a for loop based off of that.
if u need string 3 times just do
string x = "hello";
string combined = x + x + x;