charCodeAt to C# conversion - c#

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

Related

Trying to extract code in the middle of a String

I am trying to extract a code from a string. The string can vary in content and size but I am using Tag words to make the extraction easier. However, I am struggling to nail a particular scenario. Here is the string:
({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}
What I need to extract is the 011 part of {MP.011}. The keyword will always be "{MP." It's just the code that will change. Also the rest of the expression can change so for example {MP.011} could be at the beginning, end or middle of the string.
I've got close using the following:
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.LastIndexOf("}");
String result = code.Substring(pFrom, pTo - pFrom);
However, the result is 011} + {SilverPrice as it is looking for the last occurrence of }, not the next occurrence. This is where I am struggling.
Any help would be much appreciated.
You could use a regular expression to parse that:
var str = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var number = Regex.Match(str, #"{MP\.(\d+)}")
.Groups[1].Value;
Console.WriteLine(number);
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.IndexOf("}", pFrom); //find index of } after start
String result = code.Substring(pFrom, pTo - pFrom);
the safest option is to use Regex with Negative and Positive Lookahead. This also matches multiple if you need it anyway.
var str3 = #"({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var result = Regex.Matches(str3, #"(?<=\{MP\.).+?(?=\})");
foreach (Match i in result)
{
Console.WriteLine(i.Value);
}
The key is to use the .IndexOf(string text,int start) overload.
static void Main(string[] args)
{
string code = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
// Step 1. Extract "MP.011"
int pFrom = code.IndexOf("{MP.");
int pTo = code.IndexOf("}", pFrom+1);
string part = code.Substring(pFrom+1, pTo-pFrom-1);
// Step 2. Extact "011"
String result = part.Substring(3);
}
or you can combine the last statements into
String result = code.Substring(pFrom+1, pTo-pFrom-1).Substring(3);

C# How to make a return function?

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.

How to delete every 2nd character in a string?

How to delete every 2nd character in a string?
For example:
3030313535333635 -> 00155365
3030303336313435 -> 00036145
3032323437353530 -> 02247550
The strings are always 16-characters long and the result is always 8 characters long - and the character that is being removed is always a '3' - Don't ask why however - I did not dream up this crazy source data.
Try this to get the every other character from the string:-
var s = string.Join<char>("", str.Where((ch, index) => (index % 2) != 0));
String input = "3030313535333635";
String result = "";
for(int i = 1; i < 16; i +=2 )
{
result += input[i];
}
You can use this well-known class System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary :)
string str = "3030313535333635";
var hex = System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse(str);
var newstr = Encoding.ASCII.GetString(hex.Value);
Using a StringBuilder to create a string will save resources
string input = "3030313535333635";
var sb = new StringBuilder(8); // Specify capacity = 8
for (int i = 1; i < 16; i += 2) {
sb.Append(input[i]);
}
string result = sb.ToString();
Code in Java Language
String input= "3030313535333635"
String output="";
for(int i=1;i<input.length();i=i+2)
{
output+=input.charAt(i).toString();
}
System.out.println(output);

Get all instances of sub-string one at a time?

If i have a string containing three 0 values, how would i grab them one by one in order to replace them?
the 0's could be located anywhere in the string.
i don't want to use regex.
example string to parse:
String myString = "hello 0 goodbye 0 clowns are cool 0";
right now i can only find the three 0 values if they are right next to each other. i replace them using stringToParse.Replace("0", "whatever value i want to replace it with");
I want to be able to replace each instance of 0 with a different value...
You can do something like this:
var strings = myString.Split('0');
var replaced = new StringBuilder(strings[0]);
for (var i = 1; i < strings.Length; ++i)
{
replaced.Append("REPLACED " + i.ToString());
replaced.Append(strings[i]);
}
pseudolang :
s = "yes 0 ok 0 and 0"
arr = s.split(" 0")
newstring = arr[0] + replace1 + arr[1] + replace2 + arr[2] + replace3
If you have control of these input strings, then I would use a composite format string instead:
string myString = "hello {0} goodbye {1} clowns are cool {2}";
string replaced = string.Format(myString, "replace0", "replace1", "replace2");
public string ReplaceOne(string full, string match, string replace)
{
int firstMatch = full.indexOf(match);
if(firstMatch < 0)
{
return full;
}
string left;
string right;
if(firstMatch == 0)
left = "";
else
left = full.substring(0,firstMatch);
if(firstMatch + match.length >= full.length)
right = "";
else
right = full.substring(firstMatch+match.length);
return left + replace + right
}
If your match can occur in replace, then you will want to track what index your upto and pass it in to indexOf.
Using LINQ and generic function to decouple replacement logic.
var replace = (index) => {
// put any custom logic here
return (char) index;
};
string input = "hello 0 goodbye 0 clowns are cool 0";
string output = new string(input.Select((c, i) => c == '0' ? replace(i) : c)
.ToArray());
Pros:
Char replacement logic decoupled from the string processing (actually LINQ query)
Cons:
Not the best solution from performance perspectives

Split a string without separator

I have a string variable with value
"abcdefghijklmnop".
Now I want to split the string into string array with, say, three characters (the last array element may contain fewer) in each array element from the right end.
I.e.,
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
What is the easiest and simplest way to do this?? (Both Visual Basic and C# code is welcome)?
Here's a solution:
var input = "abcdefghijklmnop";
var result = new List<string>();
int incompleteGroupLength = input.Length % 3;
if (incompleteGroupLength > 0)
result.Add(input.Substring(0, incompleteGroupLength));
for (int i = incompleteGroupLength; i < input.Length; i+=3)
{
result.Add(input.Substring(i, 3));
}
It gives the expected output of:
"a"
"bcd"
"efg"
"hij"
"klm"
"nop"
Here's something that works - wrapped up into a string extension function.
namespace System
{
public static class StringExts
{
public static IEnumerable<string> ReverseCut(this string txt, int cutSize)
{
int first = txt.Length % cutSize;
int taken = 0;
string nextResult = new String(txt.Take(first).ToArray());
taken += first;
do
{
if (nextResult.Length > 0)
yield return nextResult;
nextResult = new String(txt.Skip(taken).Take(cutSize).ToArray());
taken += cutSize;
} while (nextResult.Length == cutSize);
}
}
}
Usage:
textBox2.Text = "";
var txt = textBox1.Text;
foreach (string s in txt.ReverseCut(3))
textBox2.Text += s + "\r\n";
Regex time!!
Regex rx = new Regex("^(.{1,2})??(.{3})*$");
var matches = rx.Matches("abcdefgh");
var pieces = matches[0].Groups[1].Captures.OfType<Capture>().Select(p => p.Value).Concat(matches[0].Groups[2].Captures.OfType<Capture>().Select(p => p.Value)).ToArray();
pieces will contain:
"ab"
"cde"
"fgh"
(Please, don't use this code! It is only an example of what can happen when you use a regular expression + LINQ.)
Well... here is yet another way I arrived at:
private string[] splitIntoAry(string str)
{
string[] temp = new string[(int)Math.Ceiling((double)str.Length / 3)];
while (str != string.Empty)
{
temp[(int)Math.Ceiling((double)str.Length / 3) - 1] = str.Substring(str.Length - Math.Min(str.Length, 3));
str = str.Substring(0, str.Length - Math.Min(str.Length, 3));
}
return temp;
}

Categories