Null character deleting rest of output in TextBox and RichTextBox [duplicate] - c#

This question already has an answer here:
ASCII.GetString() stop on null character
(1 answer)
Closed 6 years ago.
I have came across this annoying feature/bug. Assume I have a string with trailing spaces like the following:
string value = "someValue ";
The amount of spaces can vary. So I try to show it in a TextBox enclosed in begin and end tags to see how it varies, and it works perfectly.
textBox1.Text = $"BEGIN#{value}#END";
But the device that send me this value likes to add a \0 null character at the end like this:
string value = "someValue " + Convert.ToChar(0x00);
and when I try to display it with the same method:
textBox1.Text = $"BEGIN#{value}#END;
it results in the disappearance of the #END tag.
The same phenomenon happens in RichTextBox.
Question:
Why does the null character kills/eats the rest of the string?
Is it like in C or C++ that it is interpreted as the end of the char array in a string?

In some languages, such as C and C++, a null character indicates the end of a string. In the .NET Framework, a null character can be embedded in a string. When a string includes one or more null characters, they are included in the length of the total string. For example, in the following string, the substrings "abc" and "def" are separated by a null character. The Length property returns 7, which indicates that it includes the six alphabetic characters as well as the null character.
using System;
using System.Text;
public class StringClassTest
{
public static void Main()
{
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7
}
}

Related

How to find the immediate integer value written before a string? [duplicate]

This question already has answers here:
How to get the digits before some particular word using regex in c#?
(8 answers)
Closed 2 years ago.
How to find the immediate integer value written before a string in c#? For example
50+ boxes were ordered, however only 2 are delivered.
I need to know the number of boxes (integer value) written just before "delivered". The output should be 2. I have written a code in c# using Regex:
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"\d+").Value;
//The output I get is 50 instead of 2.
To get the last number that is followed by the word "delivered", you may use the following pattern:
\b\d+\b(?=[^\d]*\bdelivered\b)
Regex demo.
Here's a full example:
string line = "50+ boxes were ordered, however only 2 are delivered.";
var match = Regex.Match(line, #"\b\d+\b(?=[^\d]*\bdelivered\b)");
if (match.Success)
{
string boxesDelivered = match.Value;
// TODO: convert the value to a numeric type or use it as is.
}
Try it online.
written just before delivered
I'm going to take that verbatim as your user requirement - find the last number in the string that appears before "delivered".
You can use (\d+)[^\d]*(?:delivered), which says "match any sequence of numbers that does not occur before another sequence of numbers and does occur before delivered".
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"(\d+)[^\d]*(?:delivered)").Groups[1].Value;
// boxesDelivered = 2

Removing all occurences of '\' from json response string not working [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 3 years ago.
List item
I have a string object such as the following.
string mycontent = "\"The time is Valid\"\n"
string tocompare = "The time is Valid"
The contents of mycontent are assigned by the following line of code.
string mycontent = await response.Content.ReadAsStringAsync();
I want to be able to remove all the \n and the \ and to do that I do the following.
mycontent.Trim().Replace(#"\","")
I am trying to compare the mycontent and tocompare for equality. But this does not work.
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","")) == 0)
{
//TODO
}
For some reason which I do not know, I am not able to see equal to 0.
Am I missing something here? Any help is appreciated.
There are no actual slash characters in the string you showed. The slashes in the source code are part of the string literal syntax, where the \" represents just the character " (it needs to be escaped to distinguish it from the end of the string) and the \n represents a newline.
If you want to remove quotes and newlines from the sides of the string, you can do that with Trim too:
mycontent.Trim('"', '\n')
But that’s a bit of a weird thing to do. If this string actually represents some serialized format for the text you want, like JSON or CSV, you should use a parser for that instead. Where did you get it?
You have to replace slash first and then the quote
mycontent = mycontent.Trim().Replace(#"\", "").Replace(#"""", "")
In your case:
if (string.Compare(tocompare, mycontent.Trim().Replace(#"\","").Replace(#"""", "")) == 0)
{
//TODO
}
If you want to add a text slash to a string, you must type like this.
string mycontent = "\\"+"The time is Valid"+"\\"+"\n";
To delete slashes
mycontent=mycontent.Trim().Replace("\\","");

Performing OR in regex capture groups [duplicate]

This question already has answers here:
Using alternation and grouping constructs
(2 answers)
Closed 4 years ago.
I would like a match if the value contains either digits or matches the pattern [lookup('key')] where key can be any string.
Using either pattern on its own works. For example this works.
string value = "[lookup('anykey')]";
if (!Regex.IsMatch(value, "^\\[(lookup)\\(.*\\)\\]$"))
{
Console.WriteLine("no match");
}
I couldn't get both to work with a single regex.
if (!Regex.IsMatch(value, "((\\d+) | (\\[(parameter)\\(.*\\)\\]))"))
{
Console.WriteLine("no match");
}
Any idea?
In your regex you should remove spaces, try:
\d+|\[lookup\('[^']+'\)\]
First of all whenever I use regular expression in c# or for that matter any string that has characters that require escaping I prefix the string with '#' symbol, which saves me from using double escapes:)...I find it easier
Ok now to the answer, here is what I think you are looking for
static void Main(string[] args)
{
//string value = "[lookup('BlahBlah')]";
string value = "789897";
Match m = Regex.Match(value, #"((\d+)|(\[lookup\(\'([^\']+)\'\)\]))") ;
if (m.Success)
{
string num = m.Groups[2].Value;
string key = m.Groups[4].Value;
}
}
Notice how the string was prefixed with the '#' symbol and I didn't have to use double escapes for symbol \.
Since we are using so many parenthesis, we have 5 groups overall and if you want the number then you take the value of group 1, if you want the key the you take the value of group 4. If the 'num' is an empty string that means no number was supplied etc...
Hope that helps .....

Removing characters from a string passed from an HTML page [duplicate]

This question already has answers here:
How to remove new line characters from a string?
(11 answers)
Closed 9 years ago.
I'm trying to trim a string of some character so I can put it in an SQL query. An example of what is being passed to my method is "\n asdw_value\n". I want the "\n"s and the space to be removed, but I can't get the "\n" to go away. My code now looks like this :
element = element.Replace("\\", "");
element = element.Replace("n", "");
element = element.Replace(" ", "");
And the output has been "\nasdq_value\n" Any help is appreciated.
Most likely the string value you're seeing is produced in the debugger. The \n is an escape sequence meaning 'newline'. It's a single character, not a \ followed by a n, so to remove it from your input, you will need to use the same escape sequence, like this:
element = element.Replace("\n", "");
element = element.Replace(" ", "");
If you only want to trim these characters from the beginning and end of the string, you can do this:
element = element.Trim(new char[] { '\n', ' ' });

Check if string has space in between (or anywhere) [duplicate]

This question already has answers here:
Detecting whitespace in textbox
(4 answers)
Closed 4 years ago.
Is there a way to determine if a string has a space(s) in it?
sossjjs sskkk should return true, and sskskjsk should return false.
"sssss".Trim().Length does not seem to work.
How about:
myString.Any(x => Char.IsWhiteSpace(x))
Or if you like using the "method group" syntax:
myString.Any(Char.IsWhiteSpace)
If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:
string s = "Hello There";
bool fHasSpace = s.Contains(" ");
If you're looking for ways to detect whitespace, there's several great options below.
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(#"\s");
regex.IsMatch(text); // true
Trim() will only remove leading or trailing spaces.
Try .Contains() to check if a string contains white space
"sossjjs sskkk".Contains(" ") // returns true
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}

Categories

Resources