Concatenating a char with an int and a string does odd things - c#

I was coding and needed to build up a file name. I wanted to separate the parts of the file names by an _.
I figured that since I only wanted to add on char in I could use '_'.
int id = 125;
string testWithChar = id + '_' + "Something";
Console.WriteLine(testWithChar);
But when I do I get this:
220Something
Kind of odd.
But if I do it right:
int id = 125;
string testWithString = id + "_" + "Something";
Console.WriteLine(testWithString);
I get the expected output:
125_Something
But I am curious. What is really happening in the first one to give me a different number?

The reason is, C# is considering the char as it's unicode value, and thus the addition between them does not add strings, but integers.
_ in ascii is 95, and thus
int id = 125;
string testWithChar = id + '_' + "Something";
is the equivallent of:
string testWithChar = 125 + 95 + "Something";
In contrast, when you add "_", the addition is done between a string and an integer - and the operator just appends the string to it.

The int value of a char is its place in the ASCII table. '_' is at place 95

When you add an integer to another numeric type, you end up with the result of the addition, rather than the concatenation. In this case, char is a numeric value, so 125 + 95 (value of '_') concatenated with your string gives you 220_Something.
I'd create the string as string.Format("{0}_{1}", id, "Something") instead, particularly as your final string gets more complicated.

The int value is replaced with its ASCII value of 95.
Using string formatting is the most safe way:
Console.WriteLine("{0}_Something", id);

Related

Convert string to unicode in C#?

How can I get the unicode values (from the code column) if I have the string?
For example, for passing the empty space " " I would like to get the value U+0020.
I found this approach:
byte[] asciiBytes1 = Encoding.ASCII.GetBytes(" ");
But this returns me the value from the decimal column.
If value is your decimal value:
string code = $"U+{value.ToString ("X4")}";
will give you what you want.
(X means hex, 4 means pad to 4 digits)

How to replace multiple characters in a string with other multiple characters (another string) without replacing other ocurrences?

I'm making a console application for IP assignment where a user simply enters the number of networks, the number of hosts per network and the initial network IP address, and this generates the full IP assignment table.
My biggest issue right now is that say I have a string with "172.16.0.0".
I want to grab the 0 at the end, convert it to an int, add a certain number of hosts (say, 0 + 512), and if it goes over 255, I want it to instead grab the previous 0 and replace it with a 1 instead then test it again. But I'm mostly having issues with replacing the numbers in the initial string. Since strings aren't mutable, I obviously have to make a new string with the change, but I can't see how to do this.
I've so far tried finding the index where the change will be made using the string.split function and indexof and making that an int variable called datIndex. Then I change the "172.16.0.0" string to a character array, then tried swapping the character in the previously defined index, however this limits me to a single character, which wouldn't work for a number with more than one digit. Also tried using stringbuilder but the stringbuilder object seems to be a char type so I end up in the same place, can't equal the value in the index I want to change to the new number.
string test = "172.16.0.0";
int datIndex = test.IndexOf(test.Split('.')[2]);
char[] c = test.ToCharArray();
c[datIndex] = '201'; //Not possible because more than one digit
//Also tried the following
datIndex = test.IndexOf(test.Split('.')[2]);
StringBuilder sb = new StringBuilder(test);
sb[datIndex] = '201'; //Cannot implicitly convert type string to char
string temp2 = sb.ToString();
test = temp2; //Changed string
In this example, I'd like to change the penultimate "0" in the "172.16.0.0" string to a "201" (this number would be obtained by a sum of two numbers so ideally they'd both first be integers).
However with both methods I've tried, I can't fit a number bigger than one digit into that index.
This is maybe what you are looking for:
string ip = "127.16.0.0";
string ipNumbers = ip.Split('.');
int a = int.Parse (ipNumbers[0]);
int b = int.Parse (ipNumbers[1]);
int c = int.Parse (ipNumbers[2]);
int d = int.Parse (ipNumbers[3]);
//now you have in a,b,c and d all the ip numbers, do the math with them and then do this:
ip = $"{a}.{b}.{c}.{d}";

Convert hexadecimal string to an integer

int value = Convert.ToInt32('o');
Byte[] b = new Byte[] { ( byte)value };
File.WriteAllBytes(Default.ProjectsPath , b);
when I open the file it displays o, I want to write the byte value to the file?
Remove the0x then convert:
int i = Convert.ToInt32("0xFE".Substring(2), 16);
Convert.ToInt16(string) will not be able to convert strings that start with '0x', even though that's the correct notation for base 16 numbers. If you want to use your solution, you will need to remove the "0x" from the string conversion. Replace
string s=String.Format("0x{0:X}", value);
with
string s=String.Format("{0:x}", value);
Or you can use Alex K.'s idea and replace
int x=Convert.ToInt16(s);
with
int x=Convert.ToInt16(s.Substring(2));
if you are the one producing the string in the first place then like Alex Barac suggested, dont place a 0x prefix at all... (why create problems you dont need)
if you have to have the prefix, use it... if the prefix is '0x' use
int i = Convert.ToInt32("0xFE".Substring(2), 16); as Alex K. suggested
if it is not '0x', then it probobally a Base10 number:
int i = Convert.ToInt32("342", 10);

Is there a way to concat string with char as a const?

If I try
const char NoChar = (char)8470; //№
const char TmChar = (char)8482; //™
const string IdDisplayName = "Clements" + TmChar + ' ' + NoChar;
it will throw a compile error:
The expression being assigned to '{0}' must be constant
As far as I understand, this error occurs because when a char is because the string concatenation operator (+) internally calls ToString on the concatenated object.
My question is if there is a way (unmanaged?) to do it.
I need to pass that constant as an attribute and it should be generated on client.
The uglier workaround (will see what's uglier based on your answers...) is to subclass that attribute (which is sealed, will have to make some decompilation and copy-paste work) and embedding it as a non-const will be possible.
You're allowed to specify unicode character values directly in a string via the \u escape. So const string IdDisplayName = "Clements\u2122 \u2116"; should get you what you want.
I assume that simply:
const string NoChar = "\x2116"; //№ - Unicode char 8470
const string TmChar = "\x2122"; //™ - Unicode char 8482
const string IdDisplayName = "Clements" + TmChar + " " + NoChar;
Is unacceptable?

Copy first few strings separated by a symbol in c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Categories