C# How to make a return function? - c#

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.

Related

How to add two strings that are numbers? [duplicate]

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

charCodeAt to C# conversion

I want to convert this (ActionScript) function to C#, but can't figure out the charCodeAt
var _local_2 = "g";
var _local_3 = "h";
var _local_4:String = this.keycode((((((((("m" + _local_3) + "w") + _local_2) + "ffvn") + _local_2) + "63") + _local_3) + "d8"));
private function keycode(_arg_1:String):String{
var _local_2:* = "";
var _local_3:int;
while (_local_3 < _arg_1.length) {
_local_2 = (_local_2 + String(_arg_1.substr(_local_3, 1)).charCodeAt(0));
_local_3++;
};
return (_local_2);
}
and output value of above keynote function on _local_4 is
109104119103102102118110103545110410056
But I don't know what should I use charCodAt in C# and get the ascii values.
Please help me convert it.
Thanks and Regards.
You can use indexer for getting the specific charcter from the string.
i think you want to get the first character from the substring, so you can use [0].
var _local_2 += _arg_1.Substring(_local_3, 1)[0].ToString();
It seems you are just trying to return a substring with one character and then get char code (ascii value?) which you can get from using the index
var _local_2 += _arg_1[_local_3];
Tested using the following function
static int characterCount(string s)
{
int result = 0;
foreach (var c in s)
result += c;
return result;
}
//"test" == 448

How do I convert part of a string to int in C#? [duplicate]

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", "");

How to convert string to integer in C#

How do I convert a string to an integer in C#?
If you're sure it'll parse correctly, use
int.Parse(string)
If you're not, use
int i;
bool success = int.TryParse(string, out i);
Caution! In the case below, i will equal 0, not 10 after the TryParse.
int i = 10;
bool failure = int.TryParse("asdf", out i);
This is because TryParse uses an out parameter, not a ref parameter.
int myInt = System.Convert.ToInt32(myString);
As several others have mentioned, you can also use int.Parse() and int.TryParse().
If you're certain that the string will always be an int:
int myInt = int.Parse(myString);
If you'd like to check whether string is really an int first:
int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
int plusOne = myInt + 1;
}
int a = int.Parse(myString);
or better yet, look into int.TryParse(string)
string varString = "15";
int i = int.Parse(varString);
or
int varI;
string varString = "15";
int.TryParse(varString, out varI);
int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.
Do something like:
var result = Int32.Parse(str);
If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.
string s="4";
int a=int.Parse(s);
For some more control over the process, use
string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
// it's int;
}
else {
// it's no int, and there's no exception;
}
4 techniques are benchmarked here.
The fastest way turned out to be the following:
y = 0;
for (int i = 0; i < s.Length; i++)
y = y * 10 + (s[i] - '0');
"s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.
At the end, "y" will have your int value.
int i;
string whatever;
//Best since no exception raised
int.TryParse(whatever, out i);
//Better use try catch on this one
i = Convert.ToInt32(whatever);
bool result = Int32.TryParse(someString, out someNumeric)
This method will try to convert someString into someNumeric, and return a result depending on whether or not the conversion is successful: true if conversion is successful and false if conversion failed. Take note that this method will not throw an exception if the conversion failed like how Int32.Parse method did and instead returns zero for someNumeric.
For more information, you can read here:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#
int i;
string result = Something;
i = Convert.ToInt32(result);
You can use either,
int i = Convert.ToInt32(myString);
or
int i =int.Parse(myString);
class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}

Multiplying strings in C# [duplicate]

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;

Categories