I want to find a way to check if a string contains text and if it does it will go to to the next one and keep doing this till it finds an empty string or reached the end.
The issue is I can't find anything that I could use to check if the string is containing any text, I can only find if it a IsNullOrWhiteSpace or if it contains a specific text.
When does a string contain text? Well when the string exists and it does not contain an empty text. When does a string contain an empty text? When the length of the string is 0.
So, answering your question, a text is not empty when it exists and s.Length != 0:
if (s != null && s.Length > 0) { /*s is not empty*/ }
or better yet
if (s?.Length > 0) { /*s is not empty*/ }
or if you prefer a string contains text when it is not nonexistant or empty:
if (!string.IsNullOrEmpty(s)) { /*s is not empty*/ }
Now if texts consisting only of whitespaces must also be considered as empty, then when is a text not empty? When the text is anything but nonexistant or empty spaces, that is, IsNullOrWhiteSpace is false:
if (!string.IsNullOrWhiteSpace(s)) { /*s is not empty*/ }
Related
I'm making a console adventure game for practice and I need to display a text when my character close to an object (at adjacent position). This string must be displayed until the character close to the object, but if it step further the text need to gone.
I tried this:
if (field[ver, hor + 1] == '█')
{
notice_detection = "DETECTION: '█' (right)";
Console.SetCursorPosition(37, 0);
Console.Write(notice_detection);
}
else
{
if (notice_detection != null)
{
notice_detection = " ";
Console.SetCursorPosition(37, 0);
Console.Write(notice_detection);
}
}
It's working but not too elegant. I'm sure a better solution exist.
My first try was to put 'notice_detection.Remove(0)' into else, but its didn't remove the already displayed string (by the way, why it's happened?).
Thanks!
The .Remove() method on strings returns a new string containing the remaining characters that are not removed starting from the given index. Calling it with 0 means that it removes everything from index 0 and returns the remaining, an empty string. If you write an empty string to the console, that looks like it does not did anything.
You can also replace your whitespacing hard coded string with a dynamic sized one filled with whitespaces like this:
var clearChars = new string(' ', notice_detection.Length);
Console.SetCursorPosition(37, 0);
Console.Write(clearChars);
So I have a Label being initialized by a WebService. I want to see if that label contains any commas. The problem is, even if the label has commas, Contains() returns false and if I do a Split(), the array is only 1 element long, containing the entire string.
// text is "255,255,0,0"
string wat = myLabel.Text;
string[] wats = wat.Split(',');
// This IF never happens, for some reason
if (wat.Contains(","))
{
anotherLabel.Text = wats[0] + " VS " + wats[1];
}
Why don't Split() and Contains() work? Can it be some kind of diferent encode in the string that comes from the label? If I do wat = wat + ",", then Contains()returns True.
Unicode symbols are often weird. Unicode has a lot of commas, e.g.
string wat = "255,255,0,0"; // Full range commas
bool hasComma = wat.Contains(','); // false
If wat.Contains(',') returns false then delimiters are not commas ,. You can check it with string decoded:
string wat = myLabel.Text;
// Let's have a close look at wat: which characters (codes included) does it contain
MessageBox.Show(
$"wat: [{wat}] encoded as {string.Join(" ", wat.Select(c => ((int)c).ToString("x4")))}");
You should get
wat: [255,255,0,0] encoded as 0032 0035 0035 002c 0032 0035 0035 002c
0030 002c 0030
if not check what character code(s) do you have instead of expected 002c.
The following line is always going to evaluate to false:
if (wats.Contains(","))
string.Split(',') will only return the values in between commas as you are specifying a comma as your delimiter. None of the items in the array will ever contain a comma.
If you want to check whether your label text contains commas simply do:
if (lblteste.Text.Contains(','))
I am trying to pick out specific letters/numbers from a text box, because each means something. After that I am trying to display in a label what it means.
So if I have a number AB-123456, I need to first pick out AB something like:
If (textBox.Text.Substring(0,2) == "AB") {
//Display to a label
}
First off, this doesn't work and I also tried substring(0,1) but also was receiving errors when I used my clear button to clear the text box.
After that I still need to pull the rest of the numbers. The next one I need to pull and define is 123, then 4 by itself, 5 by itself, and six by itself.
How do I go about pulling each of these individually if substring isnt working?
Try this:
if (textBox.Text.StartsWith("AB"))
{
//Display to a label
}
Use this if you don't want to have to check the Length of the text first. Also, you can include a StringComparison argument if you want to ignore case.
string input = textBox.Text;
// check the length before substring
If (input.Length >= 2 && input.Substring(0,2) == "AB") {
//Display to a label
}
or use regex:
string txt="AB-1234562323";
string re="AB-(\\d+)"; // Integer Number 1
Regex r = new Regex(re,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)// match found
{
// get the number
String number=m.Groups[1].ToString();
}
So I'm writing some code and using RegistryKey.GetValue and I can't seem to get it to return the proper string array. I would use RegSaveKeyEx except I need to change the location of where the keys are being saved to in the reg file I'm creating.
The MultiString I'm querying has two lines in it, : and a blank line. Regedit gives hex(7):3a,00,00,00,00,00 for the reg file export of said value. This is correct. 3a would be :, then a null, two nulls for the blank line and finally two more nulls to signify the end of the value. My code is giving hex(7):3a,00,00,00, which would be a : and the double-null EOL characters on a MultiString. When imported back into the registry hex(7):3a,00,00,00 is only a :, the blank line is missing.
If I import hex(7):3a,00,00,00,00,00 then view the value in regedit, I see : and a blank line. This is correct and this is what I want my code to do.
When I query this value with RegistryKey.GetValue in C# 4.0 I get the a string[] with just one element, the :.
For other MultiString values I get an array containing an element for every line, as I would expect.
RegistryKey.GetValue doesn't return anything for the blank line. It doesn't return a null, a blank string in the array, nothing.
On everything except blank lines it returns exactly the same result as regedit export. What needs to be changed to have it return an array that includes the blank line?
Here's my code if that's helpful:
private static string RegMultiStringExtraction(RegistryKey UsersSubKey, string Key)
{
string[] InputStrs = (string[])UsersSubKey.GetValue(Key, Environment.NewLine, RegistryValueOptions.DoNotExpandEnvironmentNames);
StringBuilder sb = new StringBuilder();
foreach (string str in InputStrs)
{
char[] Values = str.ToCharArray();
foreach (char letter in Values)
{
int ValueInt = Convert.ToInt32(letter);
sb.Append(ValueInt.ToString("x"));
sb.Append(",00,");
if (Values.Length == 0)
{
if (sb.Length == 0)
{
sb.Append("00,");
}
else if (sb.Length > 1)
{
sb.Append(",00,");
}
}
}
sb.Append("00,00,");
}
string Value = ('"' + Key.ToString() + #"""=" + "hex(7):" + sb.ToString().TrimEnd(','));
return Value;
}
Double null-terminated strings cannot contain empty lines. An attempt to include empty lines means including two consecutive nulls, and that is interpreted as termination rather than an empty line. Raymond Chen discussed this quirk much more eloquently that I can.
Perhaps you can save to REG_SZ and use Environment.NewLine as a delimiter.
I am somehow unable to determine whether a string is newline or not. The string which I use is read from a file written by Ultraedit using DOS Terminators CR/LF. I assume this would equate to "\r\n" or Environment.NewLine in C#. However , when I perform a comparison like this it always seem to return false :
if(str==Environment.NewLine)
Anyone with a clue on what's going on here?
How are the lines read? If you're using StreamReader.ReadLine (or something similar), the new line character will not appear in the resulting string - it will be String.Empty or (i.e. "").
Are you sure that the whole string only contains a NewLine and nothing more or less? Have you already tried str.Contains(Environment.NewLine)?
The most obvious troubleshooting step would be to check what the value of str actually is. Just view it in the debugger or print it out.
Newline is "\r\n", not "/r/n". Maybe there's more than just the newline.... what is the string value in Debug Mode?
You could use the new .NET 4.0 Method:
String.IsNullOrWhiteSpace
This is a very valid question.
Here is the answer. I have invented a kludge that takes care of it.
static bool StringIsNewLine(string s)
{
return (!string.IsNullOrEmpty(s)) &&
(!string.IsNullOrWhiteSpace(s)) &&
(((s.Length == 1) && (s[0] == 8203)) ||
((s.Length == 2) && (s[0] == 8203) && (s[1] == 8203)));
}
Use it like so:
foreach (var line in linesOfMyFile)
{
if (StringIsNewLine(line)
{
// Ignore reading new lines
continue;
}
// Do the stuff only for non-empty lines
...
}