I would like to know why some things have to be within a pair of Apostrophes and others within Quotation marks?
void trythis(){
char myChar = 'Stuff';
String myString = "Blah";
int myInteger = '22';
Serial.print(myChar );
Serial.print(myString );
Serial.print(myInteger );
}
Number should have no quotes int x= 56
characters have single quotes char ch = 'a';
strings have double quotes string name = "Bob";
Character literals use a single quote. So when you're dealing with char, that's 'x'.
String literals use double quotes. So when you're dealing with string, that's "x".
A char is a single UTF-16 code unit - in most cases "a single character". A string is a sequence of UTF-16 code units, i.e. "a piece of text" of (nearly) arbitrary length.
Your final example, after making it compile, would look something like:
int myInteger = 'x';
That's using a character literal, but then implicitly converting it to int - equivalent to:
char tmp = 'x';
int myInteger = tmp;
The code you wrote doesn't compile at all.
Single quotes are used for character literals (single characters, which are stored as UTF-16 in .NET). Integers are not quoted.
This would be valid:
char myChar = 's';
string myString = "Blah";
int myInteger = 22;
Related
My requirement
If string contains single slash (/ or \) it should be replace with
double slash
Note :- string is randomly generated so, I have no control.
e.g. I have string
string str = #"*?i//y\^Pk#t9`n2";
When I tried as
str = str.Replace(#"\", #"\\").Replace(#"/",#"//");
it replaced // with //// but I need to replace only single slash(\) with double slash(\\).
Above code actual result is
*?i////y\^Pk#t9`n2
expected result is
*?i//y\\^Pk#t9`n2
Note :- If string contain double slash in sequence like "//" or "\\" then no need to modify string. but string contains single slash (/ or \) need to replace with double slash.
I have tried to find out other approach then I found following stack-overflow already question-answer
Replace single backslash with double backslash
Replace "\\" with "\" in a string in C#
How to change backslash to double backslash?
Question :-
How to check if string contain single slash and how to replace it?
What best practice should follows while doing string manipulation like this?
Edit :-
I have random generated string comes from user like.
string str = #"*?i//y\^Pk#t9`n2";
sometimes that string contain single slash as above (\). if we consider above string without verbatim(#) it is not a valid string in C#. it gives compile time error. to make above string valid I need to replace "\" with "\\".
How I can achieve this?
Pls try this, first i repleced all double slash with single slash and then vice versa:
var str = #"*?i//y\^Pk#t9`n2";
var tempStr = str.Replace(#"\\", #"\").Replace(#"//",#"/");
var result = tempStr.Replace(#"\", #"\\").Replace(#"/",#"//");
I had to do two Regex.Replace and use look arounds to achieve this. The final solution was
Regex.Replace(Regex.Replace(str, #"(?<!\/)\/(?!\/)", #"//"), #"(?<!\\)\\(?!\\)", #"\\")
If you've never dealt with regex before, it can be a beast. Essentially I am looking for all backslashes and forward slashes (\\ and \/ escaped) and once I match a backslash and forward slash, I am going to use negative lookbehinds and negative aheads to not match if it there is a match in front or behind it.
Negative Look Behind:
(?<!\/)
Negative Look Ahead:
(?!\/)
I am then repeating it twice for forward slashes and backwards slashes
The best solution might be to roll your own algorithm. Step through the string character by character looking for a slash, and if it finds one, check the next character and previous, if 1 of those exist, then do not insert a duplicate slash because that means it is not alone
This replaces all of the individual occurrences of a character and also fills up an odd number of occurrences:
public static string ReplaceSingle(this string s, char needle)
{
var valueSpan = s.AsSpan();
var length = valueSpan.Length * 2;
char[]? resultArray = null;
Span<char> resultSpan = length <= 256
? stackalloc char[length]
: (resultArray = ArrayPool<char>.Shared.Rent(length));
var value = char.MinValue;
var written = 0;
for (int index = 0; index < valueSpan.Length; index++)
{
value = valueSpan[index];
resultSpan[written++] = value;
if (value == needle && ++index < valueSpan.Length)
{
value = valueSpan[index];
resultSpan[written++] = value == needle ? value : needle;
}
}
var result = new string(resultSpan[..written]);
resultSpan.Clear();
if (resultArray is not null) ArrayPool<char>.Shared.Return(resultArray);
return result;
}
For instance, if you have / it will turn to //, but // will remain. However /// will turn to //// and so on.
There is also a usage of ArrayPool and stackalloc which are aimed at better performance.
Usage:
string value = "This/ is a //Test ///!";
string result = value.ReplaceSingle('/');
var a = "asdfgh\r";
Console.WriteLine(a.Contains(#"\r"));
var b = a.Replace(#"\r","").Replace(#"\n","");
var c = a.Replace("\r","").Replace("\n","");
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
"b" and "c" prints same string and "a" prints false,
I was trying to replace \r and \n to an empty char so first i tried below code, there's a backslash in "\r" and "\n" so i decided to use "#" before them ;
var b = a.Replace(#"\r","").Replace(#"\n","")
but this didn't work,
var c = a.Replace("\r","").Replace("\n","");
this works, so im confused when should i use "#" charachter ?
You declared string a to end with carriagereturn character:
var a = "asdfgh\r"; //it has a length of 7 when compiled
So you must replace the carriage return with nothing:
Replace("\r","")
If you had declared the string to end with "backslash r":
var a = #"asdfgh\r"; //it has a length of 8 when compiled
Then you would have succeeded in replacing "backslash r" with nothing:
Replace(#"\r","")
This would also work:
Replace("\\r","")
Because the double slash is turned into a single and then the r is a normal character so you're replacing "backslash r" and not carriagereturn
When compiling the C# compiler looks for \ in a string and converts the following character(s) according to some rule. Using # before the string turns this off. Mostly it's useful for paths. Remember that it's a compile time thing, not something you need to do to variables that hold data entered in runtime. Putting an # before a variable name means something different - allowing you to call a variable a reserved word, like string #for = "for" - deplorable practice; don't do it
Ultimately the problem is that you were inconsistent when declaring your strings - a was not a verbatim string so it really did have a single carriage return char, and then you were trying to replace using a verbatim string (and "backslash r" is a different string to "carriagereturn"
This program is a translator program that takes some symbols and converts them to normal letters.
The problem is, when I try to put some symbols like: allAlphabets.Add("[]/[]"); or: allAlphabets.Add("//"); , i get an error about the UTF-16
static void Main(string[] args)
{
string input = ""; // string input
List<string> allAlphabets = new List<string>(); // storing to a list
input = Console.ReadLine();
char[] word = input.ToCharArray();
for (int i = 0; i < word.Length; i++)
{
switch (word[i]) // switch casce
{
normal letters
case 'm':
allAlphabets.Add("[]\/[]"); // represents text as a sequence of utf-16 code units
break;
case 'n':
allAlphabets.Add("[]\[]"); // represents text as a sequence of utf-16 code units
case 'v':
allAlphabets.Add("\/"); // represents text as a sequence of utf-16 code units
break;
case 'w':
allAlphabets.Add("\/\/"); // represents text as a sequence of utf-16 code units
}
}
}
}
Does someone know a way of encoding the unrecognized escape sequence?
Thank you!
You need to use the verbatim identifier (#)
To indicate that a string literal is to be interpreted verbatim. The #
character in this instance defines a verbatim string literal. Simple
escape sequences (such as "\\" for a backslash), hexadecimal escape
sequences (such as "\x0041" for an uppercase A), and Unicode escape
sequences (such as "\u0041" for an uppercase A) are interpreted
literally. Only a quote escape sequence ("") is not interpreted
literally; it produces a single quotation mark. Additionally, in case
of a verbatim interpolated string brace escape sequences ({{ and }})
are not interpreted literally; they produce single brace characters.
allAlphabets.Add(#"[]\/[]");
or escape the backslash
allAlphabets.Add("[]\\/[]")
Additional Resources
Strings (C# Programming Guide)
Regular and Verbatim String Literals
String Escape Sequences
I need to have a number formatted with certain leading characters. Ideally the code will be obvious so that it can be easily maintained. For example, if you have a number, say an integer of 42 or a currency amount of $1234.56, for example, output the following formats:
FOO.....42 A customer specified ID number format with leading periods.
$ xxxxxxx42 Format for dollar amounts with leading x's.
$ ~~~~1,234.56 Format for printing checks with leading tilde.
This question came about while I was refactoring some ugly Regex code, and I wanted to make it easier for others to modify and maintain.
You may be interested in the PadLeft method, which pads the left part of any string with a number of characters so that the overall string length is equal to the specified length. Obviously it doesn't do anything if the string is already greater than or equal to the specified length.
The following method takes in a string, a prefix, and a character to use as padding between the prefix and the string. It does some initial validation to change null strings to empty strings and to check the string length against the desired length, and then it uses PadLeft to pad the string with the specified character:
private static string PrefixAndPad(string text, string prefix, char padChar, int length)
{
text = text ?? "";
prefix = prefix ?? "";
if (text.Length >= length) return text;
if (prefix.Length + text.Length >= length) return prefix + text;
return prefix + text.PadLeft(length - prefix.Length, padChar);
}
You could then use it like:
private static void Main()
{
// Our input strings, which are numbers converted to strins
string str1 = 42.ToString();
// The following line formats as currency ("c") then removes the currency symbol
string str2 = 1234.56.ToString("c").Replace("$", "");
Console.WriteLine(PrefixAndPad(str1, "FOO", '.', 10));
Console.WriteLine(PrefixAndPad(str1, "$ ", 'x', 11));
Console.WriteLine(PrefixAndPad(str2, "$ ", '~', 14));
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
The following string formatting should be easily understood and maintained. Use the {0,n} string format for n leading spaces, and then .Replace() to modify the string after that.
var n = 1234;
var c = "FOO";
var d = 1234.56;
var s = string.Format("{0}{1,8}", c, n); // The ",8" denotes up to 8 leading spaces.
Console.WriteLine(s);
s = string.Format("{0}{1,8}", c, n)
.Replace(' ', '.'); // Change leading space to period.
Console.WriteLine(s);
s = string.Format("$_{0,8}", n) // Up to 8 leading spaces.
.Replace(' ', 'x') // Replace spaces with 'x'.
.Replace('_', ' '); // Replace the leading underscore with space.
Console.WriteLine(s);
s = string.Format("$_{0,12:#,#.##}", d) // Decimal format with leading spaces.
.Replace(' ', '~') // Replace spaces with '~'
.Replace('_', ' '); // Replace the leading underscore with space.
Console.WriteLine(s);
Output:
FOO 1234
FOO....1234
$ xxxx1234
$ ~~~~1,234.56
What I need to do is convert a C# character to an escaped unicode string:
So, 'A' - > "\x0041".
Is there a better way to do this than:
char ch = 'A';
string strOut = String.Format("\\x{0}", Convert.ToUInt16(ch).ToString("x4"));
Cast and use composite formatting:
char ch = 'A';
string strOut = String.Format(#"\x{0:x4}", (ushort)ch);