How to escape variables in C#? - c#

I want to know if what wrong is with
this peace of code? I mean how to escape
to variables from strings (in C#)? (if I had correctly understood what escaping is.)
int i;
string s;
for(i=0;i<10;i++)
{
s="\u00A"+i;
Console.WriteLine(s);
}
(Actually I want the program to write
a sereies of unicode chatacters to make a uncode table for example 00A9=® and 00A5=¥.
Or in general I want to use a variable after backslash)
To make it simple:
string a,b;
a="t";
b="n";
Console.WriteLine("Hi\{0}All\{1}",a,b);
Which I want to type a tab and insert a new line (I know it's possible to write \n and \t in WriteLine directly but I assume we want to get the special chracter from user)
Thanks in advance. ☺

int i;
string x;
for(i=0;i<10;i++)
{
x= #"\u00A" + i; //if you want the backslash
// without # it's x= "\\u00A"+i; //so the backslash is escaped
Console.WriteLine(x);
}
Edit
for (int i = 0; i < 10; i++)
{
Console.WriteLine(
char
.ConvertFromUtf32(
int.Parse("00A"+ i, System.Globalization.NumberStyles.HexNumber)));
}
The only thing you can do about the other problem:
string a,b;
a="\t";
b="\n";
Console.WriteLine("Hi{0}All{1}",a,b);

Unicode escape sequence requires 4 digits:
for(var i = 0; i < 10; i++)
{
var x="\u000A"+i; // notice 3 zeros
Console.WriteLine(x);
}
Notes
usually you'd use "\n" for new line (or even Environemnt.NewLine) like Console.Write("\n" + i);
adding integer (or any other value) to string causes automatic call to .ToString so you can add any object to string. Often it is better to use String.Format("\n {0}", i); instead of + to provide more flexible/readable formatting (adding many strings - have better methods - search).
if you are looking for writing out characters with code to particular integer value (like 32 is space) you should cast it to char: x="\u000A"+(char)i - also you should pick printable range (like 32-42).

Related

how to add a sign between each letter in a string in C#?

I have a task, in which i have to write a function called accum, which transforms given string into something like this:
Accumul.Accum("abcd"); // "A-Bb-Ccc-Dddd"
Accumul.Accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
Accumul.Accum("cwAt"); // "C-Ww-Aaa-Tttt"
So far I only converted each letter to uppercase and... Now that I am writing about it, I think it could be easier for me to - firstly multiply the number of each letter and then add a dash there... Okay, well let's say I already multiplied the number of them(I will deal with it later) and now I need to add the dash. I tried several manners to solve this, including: for and foreach(and now that I think of it, I can't use foreach if I want to add a dash after multiplying the letters) with String.Join, String.Insert or something called StringBuilder with Append(which I don't exactly understand) and it does nothing to the string.
One of those loops that I tried was:
for (int letter = 0; letter < s.Length-1; letter += 2) {
if (letter % 2 == 0) s.Replace("", "-");
}
and
for (int letter = 0; letter < s.Length; letter++) {
return String.Join(s, "-");
}
The second one returns "unreachable code" error. What am I doing wrong here, that it does nothing to the string(after uppercase convertion)? Also, is there any method to copy each letter, in order to increase the number of them?
As you say string.join can be used as long as an enumerable is created instead of a foreach. Since the string itself is enumerable, you can use the Linq select overload which includes an index:
var input = "abcd";
var res = string.Join("-", input.Select((c,i) => Char.ToUpper(c) + new string(Char.ToLower(c),i)));
(Assuming each char is unique or can be used. e.g. "aab" would become "A-Aa-Bbb")
Explanation:
The Select extension method takes a lambda function as parameter with c being a char and i the index. The lambda returns an uppercase version of the char (c) folowed by a string of the lowercase char of the index length (new string(char,length)), (which is an empty string for the first index). Finally the string.join concatenates the resulting enumeration with a - between each element.
Use this code.
string result = String.Empty;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
result += char.ToUpper(c);
result += new String(char.ToLower(c), i);
if (i < s.Length - 1)
{
result += "-";
}
}
It will be better to use StringBuilder instead of strings concatenation, but this code can be a bit more clear.
Strings are immutable, which means that you cannot modify them once you created them. It means that Replace function return a new string that you need to capture somehow:
s = s.Replace("x", "-");
you currently are not assigning the result of the Replace method anywhere, that's why you don't see any results
For the future, the best way to approach problems like this one is not to search for the code snippet, but write down step by step algorithm of how you can achieve the expected result in plain English or some other pseudo code, e.g.
Given I have input string 'abcd' which should turn into output string 'A-Bb-Ccc-Dddd'.
Copy first character 'a' from the input to Buffer.
Store the index of the character to Index.
If Buffer has only one character make it Upper Case.
If Index is greater then 1 trail Buffer with Index-1 lower case characters.
Append dash '-' to the Buffer.
Copy Buffer content to Output and clear Buffer.
Copy second character 'b' from the input to Buffer.
...
etc.
Aha moment often happens on the third iteration. Hope it helps! :)

Converting characters in string to int in c# to pairs of digits from two strings [duplicate]

This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 6 years ago.
I want to take two string input from user in c#, and than convert them to integer by their position in array and then add them. My code is the one below.
string a = Console.ReadLine();
string b = Console.ReadLine();
int i,c,d,j;
for (i=a.Length-1;i>=0;i--)
{
c = Convert.ToInt32(a[i]);
d = Convert.ToInt32(b[i]);
j = c + d;
Console.WriteLine("{0} ",j);
Console.ReadKey();
}
This code is showing wrong output such as "99 99" for input "12 21".
I wanted to add c+d then put the sum in j. Ultimately I want to write a code for big sum problem. Where I am making mistakes?
Expected: for strings "12" and "34" output to be "46" (1+3 and 2+4).
When you use the string (array) like a[i] you are not getting what you want...
The way you are referencing the string is the problem. Even though “a” is a string... when you reference it like c = Convert.ToInt32(a[i]); a[i] is going to return something else. You want to get a[i]’s value.
c = Convert.ToInt32(a[i].ToString());
d = Convert.ToInt32(b[i].ToString());
Your looping logic does not make any sense.
You are looping for the length of the string entered into a?
If there will always only be 2 numbers why are you looping in the first place?
Why not just try:
string a = Console.ReadLine();
string b = Console.ReadLine();
int c = Int.Parse(a);
int d = Int.Parse(b);
int j = c + d
Loop doesn't make any sense,because you need to parse into integer.In your code,the variable c and d is getting the ASCII value of alphabets, instead try
int c=Int.Parse(a);
int d=Int.Parse(b);
In addition to converting a[i] and b[i] to string first (ToString method), you should rather use Int32.TryParse . It can stop unexpected exceptions from popping up later.
A basic implementation would be:
int num;
bool result = Int32.TryParse(a[i].ToString(), out num);
if (result) // some action
else // some other action
See: https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx

How do I not String.Remove anything?

I have a string that may or may not need truncating. I'm passing two non-negative integers as arguments to my program. The first one is supposed to tell the program how many characters need to be removed from the beginning of the string, and the second one tells it how many characters to remove from the end. Is there a way to do it so that zeroes work properly as input, the meaning of the code is self-evident and there are no silly conditional statements like if (removefirst != 0).
string.Remove(0, removefirst) needs the conditional statement because the first argument needs to be strictly less than the second one, says the exception message. Is there a way to do it more prettily?
Math + use Substring()?
var result = str.Substring(firstNumber, str.Length - (firstNumber + secondNumber));
DotNetFiddle Example
string yourstring = "asdf";
string result;
int firstNumber = 0;
int secondNumber = 0;
Console.WriteLine(yourstring);
result = yourstring.Substring(firstNumber, yourstring.Length - (firstNumber+secondNumber));
Console.WriteLine(result);
firstNumber = 1;
secondNumber = 1;
result = yourstring.Substring(firstNumber, yourstring.Length - (firstNumber+secondNumber));
Console.WriteLine(result);
Results
asdf
asdf
sd

Reading an int from a file returns ASCII

I'm currently making a game but I seem to have problems reading values from a text file. For some reason, when I read the value, it gives me the ASCII code of the value rather than the actual value itself when I wrote it to the file. I've tried about every ASCII conversion function and string conversion function, but I just can't seem to figure it out.
I use a 2D array of integers. I use a nested for loop to write each element into the file. I've looked at the file and the values are correct, but I don't understand why it's returning the ASCII code. Here's the code I'm using to write and read to file:
Writing to file:
for (int i = 0; i < level.MaxRows(); i++)
{
for (int j = 0; j < level.MaxCols(); j++)
{
fileWrite.Write(level.GetValueAtIndex(i, j) + " ");
//Console.WriteLine(level.GetValueAtIndex(i, j));
}
//add new line
fileWrite.WriteLine();
}
And here's the code where I read the values from the file:
string str = "";
int iter = 0; //used to iterate in each column of array
for (int i = 0; i < level.MaxRows(); i++)
{
iter = 0;
//TODO: For some reason, the file is returning ASCII code, convert to int
//keep reading characters until a space is reached.
str = fileRead.ReadLine();
//take the above string and extract the values from it.
//Place each value in the level.
foreach (char id in str)
{
if (id != ' ')
{
//convert id to an int
num = (int)id;
level.ChangeTile(i, iter, num);
iter++;
}
}
This is the latest version of the loop that I use to read the values. Reading other values is fine; it's just when I get to the array, things go wrong. I guess my question is, why did the conversion to ASCII happen? If I can figure that out, then I might be able to solve the issue. I'm using XNA 4 to make my game.
This is where the convertion to ascii is happening:
fileWrite.Write(level.GetValueAtIndex(i, j) + " ");
The + operator implicitly converts the integer returned by GetValueAtIndex into a string, because you are adding it to a string (really, what did you expect to happen?)
Furthermore, the ReadLine method returns a String, so I am not sure why you'd expect a numeric value to magically come back here. If you want to write binary data, look into BinaryWriter
This is where you are converting the characters to character codes:
num = (int)id;
The id variable is a char, and casting that to int gives you the character code, not the numeric value.
Also, this converts a single character, not a whole number. If you for example have "12 34 56 " in your text file, it will get the codes for 1, 2, 3, 4, 5 and 6, not 12, 34 and 56.
You would want to split the line on spaces, and parse each substring:
foreach (string id in str.Split(' ')) {
if (id.Length > 0) {
num = Int32.Parse(id);
level.ChangeTile(i, iter, num);
iter++;
}
}
Update: I've kept the old code (below) with the assumption that one record was on each line, but I've also added a different way of doing it that should work with multiple integers on a line, separated by a space.
Multiple records on one line
str = fileRead.ReadLine();
string[] values = str.Split(new Char[] {' '});
foreach (string value in values)
{
int testNum;
if (Int32.TryParse(str, out testnum))
{
// again, not sure how you're using iter here
level.ChangeTile(i, iter, num);
}
}
One record per line
str = fileRead.ReadLine();
int testNum;
if (Int32.TryParse(str, out testnum))
{
// however, I'm not sure how you're using iter here; if it's related to
// parsing the string, you'll probably need to do something else
level.ChangeTile(i, iter, num);
}
Please note that the above should work if you write out each integer line-by-line (i.e. how you were doing it via the WriteLine which you remarked out in your code above). If you switch back to using a WriteLine, this should work.
You have:
foreach (char id in str)
{
//convert id to an int
num = (int)id;
A char is an ASCII code (or can be considered as such; technically it is a unicode code-point, but that is broadly comparable assuming you are writing ANSI or low-value UTF-8).
What you want is:
num = (int)(id - '0');
This:
fileWrite.Write(level.GetValueAtIndex(i, j) + " ");
converts the int returned from level.GetValueAtIndex(i, j) into a string. Assuming the function returns the value 5 for a particular i and j then you write "5 " into the file.
When you then read it is being read as a string which consists of chars and you get the ASCII code of 5 when you cast it simply to an int. What you need is:
foreach (char id in str)
{
if (id != ' ')
{
//convert id to an int
num = (int)(id - '0'); // subtract the ASCII value for 0 from your current id
level.ChangeTile(i, iter, num);
iter++;
}
}
However this only works if you only ever are going to have single digit integers (only 0 - 9). This might be better:
foreach (var cell in fileRead.ReadLine().Split(' '))
{
num = Int.Parse(cell);
level.ChangeTile(i, iter, num);
iter++;
}

toString() of int e = 0000007 omits all zeros. How can I preserve them?

I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.

Categories

Resources