I had the following:
string Name = name.First + " " + name.Last;
This returns Tom Jones just fine.
In case name.First may be null or name.Last may be null, I have the following:
string SpeakerName = name.First ?? string.Empty + " " + name.Last ?? string.Empty;
What is strange is that it only returns Tom. Why is this and how can I fix it such that if null it defaults to empty string for either first or last name?
Because of the relative precedence of the ?? and + operators. Try this:
string SpeakerName = (name.First ?? "") + " " + (name.Last ?? "");
Your original example is evaluating as if it was:
string SpeakerName = name.First ?? ("" + " " + (name.Last ?? ""));
Also, read Jon's answer here: What is the operator precedence of C# null-coalescing (??) operator?
As he suggests there, this should work as well:
string SpeakerName = name.First + " " + name.Last;
Because that compiles to #L.B.'s answer below, minus the trim:
string SpeakerName = String.Format("{0} {1}", name.First, name.Last)
EDIT:
You also asked that first and last both == null makes the result an empty string. Generally, this is solved by calling .Trim() on the result, but that isn't exactly equivalent. For instance, you may for some reason want leading or trailing spaces if the names are not null, e.g. " Fred" + "Astair " => " Fred Astair ". We all assumed that you would want to trim these out. If you don't, then I'd suggest using a conditional:
string SpeakerName = name.First + " " + name.Last;
SpeakerName = SpeakerName == " " ? String.Empty : SpeakerName;
If you never want the leading or trailing spaces, just add a .Trim() as #L.B. did
string SpeakerName = String.Format("{0} {1}", name.First, name.Last).Trim();
string SpeakerName = name.First != null && name.Last != null
? string.Format("{0} {1}", name.First, name.Last)
: string.Empty;
string fullName = (name.First + " " + name.Last).Trim();
This works for either or both being null and will not return a string with leading, trailing, or only spaces.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
i have below code where string dont get concatenated
string postCode = "1245";
string city = "Stockholm";
string postCodeAndCity = postCode ?? " " + " " + city ?? " ";
I get output as 1245. Not sure why it excludes city.
But this line works
string.Concat(postCode??" ", " ", city?? " ");
so why the first approach dont work?
The ?? operator associates like this:
string postCodeAndCity = postCode ?? (" " + " " + city ?? (" "));
So if postCode is not null, it just takes postCode. If postCode is null, then it takes (" " + " " + city ?? (" ")).
You can see this from the precedence table, where ?? has lower precedence than +. Therefore + binds more tightly than ??, i.e. a ?? b + c binds as a ?? (b + c), not as (a ?? b) + c.
However, in:
string.Concat(postCode??" ", " ", city?? " ");
The commas of course have higher precedence than the ??. The equivalent using + would be:
(postCode ?? " ") + " " + (city ?? " ");
I suspect what you might want to do is:
If both postCode and city are not null, take both with a space between them.
If one is null but the other isn't, take the non-null one.
If both are null, take an empty string.
You can write this long-hand:
if (postCode != null)
{
if (city != null)
return postCode + " " + city;
else
return city;
}
else
{
if (postCode != null)
return postCode;
else
return "";
}
You can write this a bit shorter (although slightly more expensively) with:
string.Join(" ", new[] { postCode, city }.Where(x => x != null));
You should use string interpolation for this:
var output = $"{postCode} {city}"
For more information see:
https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/tokens/interpolated
Here is the offending code. I haven't done much string manipulation yet, and am currently having issues.
if (orderid != orderlist[orderlist.Count - 1])
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
}
else
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "success", response2);
}
Console.WriteLine("Response 2 is: " + response2);
logger.Log("Writing " + writepath + filename);
File.WriteAllText(writepath + filename, response2);
}
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
Console.WriteLine("String a is: " + a + "String b is: " + b + "String c is: " + c);
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
I am having issues extracting a substring, as the beginning and ending strings are the same, and therefore it is unable to differentiate the strings from each other.
Here is the main issue:
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
Is there a way I can add a check if the orderid for the ending string differs from the starting string orderid? Thanks for any help!
I was working with code that was already set to scan rather than parse JSON in the optimal fashion.
I utilized this regex to remove orderid before each number as to not cause scanner length exceptions. I also overloaded string.IndexOf as mentioned by juharr.
var regex = new Regex(Regex.Escape("orderid")); //replace first occurrence of orderid
response2 = regex.Replace(response2, "", parsecount-1);
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
logger.Log("String a is: " + a + "String b is: " + b + "String c is: " + c);
var offset = c.IndexOf(b);
//lastcheck will return 0 if it's last element in orderlist, because ending string differs for last
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, offset + lastcheck) - c.IndexOf(a) - a.Length));
}
So i have this piece of code:
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
lets suppose the name is "Phiter Fernandes", ok it will say:
Welcome, Phiter!
But if the name is just "Phiter" it will stop and not run the rest of the code.
Obviously is because there are no spaces for the substring method to retrieve the first name.
But i don't want it to skip the rest of the code, i want it to work even if there is no space.
I tried using the try catch, just like this:
try
{
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
}
catch
{
MessageBox.Show("Welcome," + name + "!");
}
It works, but there is an annoying sound when the code runs the catch.
Is there any other way around this? A different way of getting the first name, perhaps?
Try splitting the string wherever there is a space, and selecting the first element, which will always be the first name.
MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");
You can try more than one options.
Replace usign Regex.
string input = "Your string " + "whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
check if space exists.
if(name.Contains(" "))
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
trim spaces
string fullName = name;
var names = fullName.Split(' ');
string firstName = names[0];
MessageBox.Show("Welcome," + firstName + "!");
Let me know which one did you use!
When this runs:
if (Title != "") {
Server.s.Log("title found: " + Title);
if (TitleColor != "") {
NameTitle = "[" + TitleColor + Title + NameColor + "]";
} else {
NameTitle = "[" + Title + "]";
}
} else {
NameTitle = "";
}
It thinks that the title has a value, when in fact, the title is most definitely just "", help me please?
You may be confusing an empty string with a null value. Try this:
if (!string.IsNullOrEmpty(Title))
or this:
if (!string.IsNullOrWhitespace(Title))
depending on your needs.
Are you sure it is an empty string and not null? Those are different. If it could be either, you can use String.IsNullOrEmpty().
I believe Title is string.
Try..
if(!string.IsNullOrEmpty(Title))
Use: String.IsNullOrEmpty(yourString))
I need to replace the characters ; and linebreak to the field p.notas. I tried this but it doesn't replace the linebreaks.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace (";" ,"."))
.Replace(Environment.NewLine , ". ");
The problem with using Environment.NewLine in your Replace() call is that the newline character(s) in your environment my not necessarily match what is actually used in the string. Yours probably has \r\n (windows) but what is actually stored is just \n. That pattern is definitely not in the string in that case. You'll have to check for all newline variants.
Assuming this is all fine in LINQ to SQL, just add more replace calls for each of the newline types.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace(";", "."))
.Replace("\r\n", ". ")
.Replace("\n", ". ")
.Replace("\r", ". ");