How can I get third and fourth letters from string? - c#

I want to get third and fourth letters from PlayerPrefs.GetString("String")
and Parse to int.
for example;
string playerLevelstr = PlayerPrefs.GetString("Player")[2] + PlayerPrefs.GetString("Player")[3];
//My Player string is "0012000000" but when I plus third and fourth letter, playerLevelstr should be "12" but it is "96".
int playerLevelint = int.Parse(playerLevelstr);

The indexer on a string returns a char.
If you use the + operator on chars together, it essentially does integer math on the two chars.
See this question for more information on that.
Though that means you should get 99 ('1' is 49, '2' is 50') not 96. But maybe that was a typo on one end or the other?
Regardless, you should either convert the chars to strings (.ToString() on them) or use the Substring function on the string instead. And don't forget your length/null checks!

This code PlayerPrefs.GetString("Player")[2] returns a char, which is being being converted to int (being the ASCII value of the character) when you add it to another char.
Do this instead:
string playerLevelstr = PlayerPrefs.GetString("Player").Substring(2,2);

Related

When I use split.string and Convert.ToInt32 the value changes, why?

For example,
string a = "4,3,2";
a.Split(',');
int one = Convert.ToInt32(a[0]);
int two = Convert.ToInt32(a[2]);
If I were to Console.WriteLine(a[0]); it will give me 4, and Console.WriteLine(a[2]) will give me 2. However, Console.WriteLine(one) and Console.WriteLine(two) gives me 52 and 50 respectively. Why is this so?
Character '4' is unicode codepoint 52 and character '3' unicode codepoint 51. You're converting characters instead of strings. The problem is that you're ignoring the result of a.Split(','); and then dereference the individual characters from a, and Convert.ToInt32(char) does:
Converts the value of the specified Unicode character to the
equivalent 32-bit signed integer.
and
The ToInt32(Char) method returns a 32-bit signed integer that
represents the UTF-16 encoded code unit of the value argument.
Instead use the strings after splitting:
string[] split = a.Split(',');
int one = Convert.ToInt32(split[0]);
int two = Convert.ToInt32(split[1]);

Convert convert int to alphabetical value

i would like to convert int's between 1-26 to the corresponding alphabetical char letter
i saw somewhere i could use char outPut = (char)currentValue; or Convert.ToChar(currentValue however both do not seem to work. i am testing this by having the program print the char to the console. both attempts have resulted in a empty character being printed
i am making a program that takes in a char letter, converts it to an int to do some maths to it and then converts the final int back to a char letter and prints the char to the console
char outPut = (char)currentValue;
would give you a char that represents some whitespace character (since those are represented as integers up to 32.)
What you actually want is a char representing a letter. The following code will give you the ith letter of the alphabet in lowercase:
char c = (char)((int)'a' + i - 1);
Or in uppercase:
char c = (char)((int)'A' + i - 1);
It uses the fact that letters are represented by consecutive integers.
You can offset by a character you want. In this case, I use 'a'.
Console.WriteLine((char)(5 + 'a'));
As your range starts with 1, you need to use 'a'-1.
int and char can be converted back and forth by using the ASCII table
ASCII value for A is 65. So you can get char A by doing
char a = (char) 65;
to convert it back using the 1-26 representation just do
int num = a - 65 + 1;
You would need to do some boundary check to make sure the number is within range of course.

C# Reducing numbers in scientific notation from E+### to E+##

Using .ToString("E4") prints a number like 1.2345E+012.
How can I make it print one less number in the exponential part. In other words, print 1.2345E+12.
Thanks!
You can use a custom format string with the E indicator, which takes the minimum number of digits:
double value = 1234567890000;
Console.WriteLine(value.ToString("0.####E+0"));
// 1.2346E+12
You could always store '.ToString("E4")' in a string called "output". Then print "output" character by character until you read a "+" character in "output". Don't print the next character if it's a "0", keep checking for "0"s until you reach something that does not equal (!=) a "0" character and then print the last characters.
Try that code:
var number = 1234567890000;
var exponential = number.ToString("E4");
var splitted = exponential.Split('+');
var result = splitted.Length == 2 ? $"{splitted[0]}+{Convert.ToInt32(splitted[1])}" : exponential;
It takes the number, evaluates the exponential string and removes all leading zeros.
This is done by splitting at the + (if there is one, otherwise it's not neccessary and there won't be any leading zeros) and converting the string, of which the zero shall get removed, to a number. As numbers aren't stored with leading zeros, converting it back to a string removes the leading zeros.
If you want to prevent cases where E+0 is written at the end, check the converted string for 0 and if so use the first part of the splitted string without the last character.

Get sub-strings from a string that are enclosed using some specified character

Suppose I have a string
Likes (20)
I want to fetch the sub-string enclosed in round brackets (in above case its 20) from this string. This sub-string can change dynamically at runtime. It might be any other number from 0 to infinity. To achieve this my idea is to use a for loop that traverses the whole string and then when a ( is present, it starts adding the characters to another character array and when ) is encountered, it stops adding the characters and returns the array. But I think this might have poor performance. I know very little about regular expressions, so is there a regular expression solution available or any function that can do that in an efficient way?
If you don't fancy using regex you could use Split:
string foo = "Likes (20)";
string[] arr = foo.Split(new char[]{ '(', ')' }, StringSplitOptions.None);
string count = arr[1];
Count = 20
This will work fine regardless of the number in the brackets ()
e.g:
Likes (242535345)
Will give:
242535345
Works also with pure string methods:
string result = "Likes (20)";
int index = result.IndexOf('(');
if (index >= 0)
{
result = result.Substring(index + 1); // take part behind (
index = result.IndexOf(')');
if (index >= 0)
result = result.Remove(index); // remove part from )
}
Demo
For a strict matching, you can do:
Regex reg = new Regex(#"^Likes\((\d+)\)$");
Match m = reg.Match(yourstring);
this way you'll have all you need in m.Groups[1].Value.
As suggested from I4V, assuming you have only that sequence of digits in the whole string, as in your example, you can use the simpler version:
var res = Regex.Match(str,#"\d+")
and in this canse, you can get the value you are looking for with res.Value
EDIT
In case the value enclosed in brackets is not just numbers, you can just change the \d with something like [\w\d\s] if you want to allow in there alphabetic characters, digits and spaces.
Even with Linq:
var s = "Likes (20)";
var s1 = new string(s.SkipWhile(x => x != '(').Skip(1).TakeWhile(x => x != ')').ToArray());
const string likes = "Likes (20)";
int likesCount = int.Parse(likes.Substring(likes.IndexOf('(') + 1, (likes.Length - likes.IndexOf(')') + 1 )));
Matching when the part in paranthesis is supposed to be a number;
string inputstring="Likes (20)"
Regex reg=new Regex(#"\((\d+)\)")
string num= reg.Match(inputstring).Groups[1].Value
Explanation:
By definition regexp matches a substring, so unless you indicate otherwise the string you are looking for can occur at any place in your string.
\d stand for digits. It will match any single digit.
We want it to potentially be repeated several times, and we want at least one. The + sign is regexp for previous symbol or group repeated 1 or more times.
So \d+ will match one or more digits. It will match 20.
To insure that we get the number that is in paranteses we say that it should be between ( and ). These are special characters in regexp so we need to escape them.
(\d+) would match (20), and we are almost there.
Since we want the part inside the parantheses, and not including the parantheses we tell regexp that the digits part is a single group.
We do that by using parantheses in our regexp. ((\d+)) will still match (20), but now it will note that 20 is a subgroup of this match and we can fetch it by Match.Groups[].
For any string in parantheses things gets a little bit harder.
Regex reg=new Regex(#"\((.+)\)")
Would work for many strings. (the dot matches any character) But if the input is something like "This is an example(parantesis1)(parantesis2)", you would match (parantesis1)(parantesis2) with parantesis1)(parantesis2 as the captured subgroup. This is unlikely to be what you are after.
The solution can be to do the matching for "any character exept a closing paranthesis"
Regex reg=new Regex(#"\(([^\(]+)\)")
This will find (parantesis1) as the first match, with parantesis1 as .Groups[1].
It will still fail for nested paranthesis, but since regular expressions are not the correct tool for nested paranthesis I feel that this case is a bit out of scope.
If you know that the string always starts with "Likes " before the group then Saves solution is better.

Convert Integer to Ascii string in C#

I want to convert an integer to 3 character ascii string. For example if integer is 123, the my ascii string will also be "123". If integer is 1, then my ascii will be "001". If integer is 45, then my ascii string will be "045". So far I've tried Convert.ToString but could not get the result. How?
int myInt = 52;
string myString = myInt.ToString("000");
myString is "052" now. Hope it will help
Answer for the new question:
You're looking for String.PadLeft. Use it like myInteger.ToString().PadLeft(3, '0'). Or, simply use the "0" custom format specifier. Like myInteger.ToString("000").
Answer for the original question, returning strings like "0x31 0x32 0x33":
String.Join(" ",myInteger.ToString().PadLeft(3,'0').Select(x=>String.Format("0x{0:X}",(int)x))
Explanation:
The first ToString() converts your integer 123 into its string representation "123".
PadLeft(3,'0') pads the returned string out to three characters using a 0 as the padding character
Strings are enumerable as an array of char, so .Select selects into this array
For each character in the array, format it as 0x then the value of the character
Casting the char to int will allow you to get the ASCII value (you may be able to skip this cast, I am not sure)
The "X" format string converts a numeric value to hexadecimal
String.Join(" ", ...) puts it all back together again with spaces in between
It depends on if you actually want ASCII characters or if you want text. The below code will do both.
int value = 123;
// Convert value to text, adding leading zeroes.
string text = value.ToString().PadLeft(3, '0');
// Convert text to ASCII.
byte[] ascii = Encoding.ASCII.GetBytes(text);
Realise that .Net doesn't use ASCII for text manipulation. You can save ASCII to a file, but if you're using string objects, they're encoded in UTF-16.

Categories