Just like the title says.
I've tried doing str.Replace("","0"); but it gave me error because oldValue has zero length.
Is it possible to replace string.Empty into something?
Edit:
I am maintaining a program and I encountered that the program was calling a method that'll return a string then be converted to Int32.
int x = Convert.toInt32(Method1());
public string Method1()
{
string retString = string.Empty;
//Do Something
return retString
}
You can simply return "0" for null, zero length or whitespace string using this one-liner:
return String.IsNullOrWhiteSpace(str) ? "0" : str;
String.Replace takes two string arguments oldValue and newValue. You specified the newValue 0 however an empty string is not legal for the oldValue.
try below code :-
str.Replace(" ","0");
or you can just assign "0" to emptry string as below :-
if(str == string.Empty)
{
str = "0";
}
or making it simple :-
String.IsNullOrWhiteSpace(str) ? "0" : str;
You can't replace empty string within the string, but you can replace, say, spaces, e.g.
str = str.Replace(" ", "0"); // providing str is not null
Or you can substitute empty string with "0":
if (String.IsNullOrEmpty(str))
str = "0";
When parsing string into int you can do something like that:
int x = String.IsNullOrEmpty(str) ? 0 : Convert.ToInt32(str);
In method() you can do:
return String.IsNullOrEmpty(retString) ? "0" : retString;
If you want to check if the value is empty and then set the value to zero, otherwise use the default value you can use an inline if like so:
return string.IsNullOrWhiteSpace(retString ) ? "0" : retString;
If you know that str is empty then you may use star="a"
If you want to check then write statement in if condition.
After your edit:
To convert an empty string to 0, and parse a non-empty string as an integer, I wouldn't deal with a "0" at all, but combine the two in a single method. For example:
int Parse(string s, int d = 0) {
if (string.IsNullOrEmpty(s))
return d;
return int.Parse(s);
}
Try This...
public string Method1()
{
string retString = string.Empty;
//Do Something
return string.IsNullOrEmpty(retString)?"0":retString;
}
It is not possible to replace string.Empty by "0". It will throw ArgumentException.
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll.
Additional information: String cannot be of zero length.
You can try following code:
if(retString == string.Empty)
{
retString = "0";
}
It sounds like your best option would be int.TryParse, if you encounter a string that can't be set to a valid value, it will set it to the default value for an integer (0) as well as returning a boolean so you can know this has happened.
int myInt;
if(!int.TryParse(myStringVariable, out myInt))
{
//Invalid integer you can put something here if you like but not needed
//myInt has been set to zero
}
//The same code without the if statement, still sets myInt
int.TryParse(myStringVariable, out myInt);
Related
So we have ?? to parse its right-hand value for when the left hand is null.
What is the equivalent for a string[].
For example
string value = "One - Two"
string firstValue = value.Split('-')[0] ?? string.Empty;
string secondValue = value.Split('-')[1] ?? string.Empty;
Above example would still crash if we would try to get a third index or if string value = "One". Because it is not null but IndexOutOfRangeException is thrown.
https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception
So what is a one-line solution to tackle the above problem? I'd like to avoid the try-catch scenario because this gives ugly code.
I want to get value out of a string[] with a string.Empty as a backup value so my string is never null.
Well, you can try Linq:
using System.Linq;
...
string thirdValue = value.Split('-').ElementAtOrDefault(2) ?? string.Empty;
However, your code has a drawback: you constantly Split the same string. I suggest extracting value.Split('-'):
string value = "One - Two"
var items = value.Split('-');
string firstValue = items.ElementAtOrDefault(0) ?? string.Empty;
string secondValue = items.ElementAtOrDefault(1) ?? string.Empty;
I suggest you create a method for this. which will accept two inputs of type string(representing the input string) and an integer(represents the specified index), and should return the split value if the specified index is available, else it will return an empty string:
string GetSubstring(string input, int index)
{
string returnValue = String.Empty;
string[] substrings = input.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
returnValue = substrings.Length > index ? substrings[index] : returnValue;
return returnValue;
}
Here is a working example for your reference
One way to achieve this is to use MoreLinq's Lead and tuple destructuring:
string value = "One - Two";
var (first, second) = value.Split('-').Lead(1, string.Empty, (x, y) => (x, y)).First();
Or, if you want a more generic approach that works for all indices:
string value = "One - Two - Three - Fourth - Fifth";
var (first, second) = value.Split('-').Skip(6).Concat(string.Empty).Lead(7, string.Empty, (x, y) => (x, y)).First();
This code will get the seventh and fourteenth entries (neither of which are there, so string.Empty will be used for both).
Another option to consider is to assign two different variables on the same line of code:
string value = "One - Two";
var split = value.Split('-');
string first = split[0] ?? string.Empty, second = split.ElementAtOrDefault(1) ?? string.Empty;
This gives you three lines of code, good performance and reasonable level of clarity and readability.
Note there is no need to use ElementOrDefault(0) - better to use [0] since Split will never return an array with no elements in it.
Another option would be to use destructuring - but that is really only useful if you are interested in contiguous entries at the start of the array (although it could be tweaked to take index parameters reasonably simply):
public static void Destructure<T>(this T[] items, T defaultValue, out T t0, out T t1)
{
t0 = items.Length > 0 ? items[0] : defaultValue;
t1 = items.Length > 1 ? items[1] : defaultValue;
}
Maybe the following code will be useful
string value = "One - Two";
string firstValue = (value.Split('-').Length == 1 ? value.Split('-')[0] : null) ?? string.Empty;
string secondValue = (value.Split('-').Length == 2 ? value.Split('-')[1] : null) ?? string.Empty;
I know how to check when a string is NullOrWhiteSpace. But i want to make my code shorter. And to return a value if my string is null or empty.
Till now i use this:
string Foo=textbox1.Text;
if(string.IsNullOrWhiteSpace(textbox1.Text);
textbox1.Text="UserName";
Is this possible to return this result using one line of code?
string Foo=textbox1.Text ?? "UserName";
In this example it returns me ""; So it thinks that my textbox it is not null, and it doesnt returns me the result i want.
Is there any working example for my case?
textbox1.Text will never be null. If the textbox is empty, it is "", not null. You might use
string Foo = string.IsNullOrWhiteSpace(textbox1.Text) ? "UserName": textbox1.Text;
The null coalescing operator just works with null. Not an empty string.
You could write an extension method to do what you want though.
public static class EX
{
public static string IfNullOrWhiteSpace(this string s, string replacement)
{
if (string.IsNullOrWhiteSpace(s))
{
return replacement;
}
return s;
}
}
Use it like this:
string Foo = textbox1.Text.IfNullOrWhiteSpace("UserName");
I used the following:
t.Description.Substring(0, 20)
But there is a problem if there are less than 20 characters in the string. Is there a simple way (single inline function) that I could use to truncate to a maximum without getting errors when the string is less than 20 characters?
How about:
t.Description.Substring(0, Math.Min(0, t.Description.Length));
Somewhat ugly, but would work. Alternatively, write an extension method:
public static string SafeSubstring(this string text, int maxLength)
{
// TODO: Argument validation
// If we're asked for more than we've got, we can just return the
// original reference
return text.Length > maxLength ? text.Substring(0, maxLength) : text;
}
What about
t.Description.Take(20);
EDIT
Since the code above would infacr result in a char array, the proper code would be like this:
string.Join( "", t.Description.Take(20));
use
string myShortenedText = ((t == null || t.Description == null) ? null : (t.Description.Length > maxL ? t.Description.Substring(0, maxL) : t));
Another:
var result = new string(t.Description.Take(20).ToArray());
Hope somebody has a good idea. I have strings like this:
abcdefg
abcde
abc
What I need is for them to be trucated to show like this if more than a specified lenght:
abc ..
abc ..
abc
Is there any simple C# code I can use for this?
Here is the logic wrapped up in an extension method:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}
Usage:
var s = "abcdefg";
Console.WriteLine(s.Truncate(3));
All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.
private string TruncateForDisplay(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
var returnValue = value;
if (value.Length > length)
{
var tmp = value.Substring(0, length) ;
if (tmp.LastIndexOf(' ') > 0)
returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
}
return returnValue;
}
public string TruncString(string myStr, int THRESHOLD)
{
if (myStr.Length > THRESHOLD)
return myStr.Substring(0, THRESHOLD) + "...";
return myStr;
}
Ignore the naming convention it's just in case he actually needs the THRESHOLD variable or if it's always the same size.
Alternatively
string res = (myStr.Length > THRESHOLD) ? myStr.Substring(0, THRESHOLD) + ".." : myStr;
Here's a version that accounts for the length of the ellipses:
public static string Truncate(this string value, int maxChars)
{
const string ellipses = "...";
return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
}
There isn't a built in method in the .NET Framework which does this, however this is a very easy method to write yourself. Here are the steps, try making it yourself and let us know what you come up with.
Create a method, perhaps an extension method public static void TruncateWithEllipsis(this string value, int maxLength)
Check to see if the passed in value is greater than the maxLength specified using the Length property. If the value not greater than maxLength, just return the value.
If we didn't return the passed in value as is, then we know we need to truncate. So we need to get a smaller section of the string using the SubString method. That method will return a smaller section of a string based on a specified start and end value. The end position is what was passed in by the maxLength parameter, so use that.
Return the sub section of the string plus the ellipsis.
A great exercise for later would be to update the method and have it break only after full words. You can also create an overload to specify how you would like to show a string has been truncated. For example, the method could return " (click for more)" instead of "..." if your application is set up to show more detail by clicking.
Code behind:
string shorten(sting s)
{
//string s = abcdefg;
int tooLongInt = 3;
if (s.Length > tooLongInt)
return s.Substring(0, tooLongInt) + "..";
return s;
}
Markup:
<td><%= shorten(YOUR_STRING_HERE) %></td>
Maybe it is better to implement a method for that purpose:
string shorten(sting yourStr)
{
//Suppose you have a string yourStr, toView and a constant value
string toView;
const int maxView = 3;
if (yourStr.Length > maxView)
toView = yourStr.Substring(0, maxView) + " ..."; // all you have is to use Substring(int, int) .net method
else
toView = yourStr;
return toView;
}
I found this question after searching for "C# truncate ellipsis". Using various answers, I created my own solution with the following features:
An extension method
Add an ellipsis
Make the ellipsis optional
Validate that the string is not null or empty before attempting to truncate it.
public static class StringExtensions
{
public static string Truncate(this string value,
int maxLength,
bool addEllipsis = false)
{
// Check for valid string before attempting to truncate
if (string.IsNullOrEmpty(value)) return value;
// Proceed with truncating
var result = string.Empty;
if (value.Length > maxLength)
{
result = value.Substring(0, maxLength);
if (addEllipsis) result += "...";
}
else
{
result = value;
}
return result;
}
}
I hope this helps someone else.
string s = "abcdefg";
if (s.length > 3)
{
s = s.substring(0,3);
}
You can use the Substring function.
Refactor with new C# features just for disclosure:
Nullables (C# 7)
Expression-bodied members (C# 6 and 7)
Ranges on strings (C# 8)
// public static class StringExtensions { ...
private static string? Truncate(this string? value, int maxChars)
=>
string.IsNullOrEmpty(value) ? value :
value.Length <= maxChars ? value :
value[..maxChars] + "...";
Checked as "Community wiki", be free to improve answer.
Sure, here is some sample code:
string str = "abcdefg";
if (str.Length > X){
str = str.Substring(0, X) + "...";
}
I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.
But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.
I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...
if (CurrentStatus.Length >= 3750)
{
// perform some truncation to free up some space.
// Lets get the status messages into an array for processing...
// We use the period as the delimiter, then skip the first item and re-insert into an array.
string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
.Skip(1).ToArray();
// Next we return the data to a string and replace any escaped returns with proper one.
CurrentStatus = (string.Join(".", statusArray))
.Replace("\\r\\n", Environment.NewLine);
}
Hope it helps someone out.
2 days ago, there was a question related to string.LastIndexOf(String.Empty) returning the last index of string:
Do C# strings end with empty string?
So I thought that; a string can always contain string.empty between characters like:
"testing" == "t" + String.Empty + "e" + String.Empty +"sting" + String.Empty;
After this, I wanted to test if String.IndexOf(String.Empty) was returning 0 because since String.Empty can be between any char in a string, that would be what I expect it to return and I wasn't wrong.
string testString = "testing";
int index = testString.LastIndexOf(string.Empty); // index is 6
index = testString.IndexOf(string.Empty); // index is 0
It actually returned 0. I started to think that if I could split a string with String.Empty, I would get at least 2 string and those would be String.Empty and rest of the string since String.IndexOf(String.Empty) returned 0 and String.LastIndexOf(String.Empty) returned length of the string.. Here is what I coded:
string emptyString = string.Empty;
char[] emptyStringCharArr = emptyString.ToCharArray();
string myDummyString = "abcdefg";
string[] result = myDummyString.Split(emptyStringCharArr);
The problem here is, I can't obviously convert String.Empty to char[] and result in an empty string[]. I would really love to see the result of this operation and the reason behind this. So my questions are:
Is there any way to split a string with String.Empty?
If it is not possible but in an absolute world which it would be possible, would it return an array full of chars like [0] = "t" [1] = "e" [2] = "s" and so on or would it just return the complete string? Which would make more sense and why?
Yes, you can split any string with string .Empty
string[] strArr = s.Split(string.Empty.ToCharArray());
You will always get an Index of 0 when you look for String.Empty in any String, because it's the definition of String.IndexOf(String.Empty) you should have a look at the MSDN, where it says:
"The zero-based index position of
value if that string is found, or -1
if it is not. If value is
String.Empty, the return value is 0."
Directed to your second Question:
I think you can Split a String with an Empty String by doing something like this in your code:
String test = "fwewfeoj";
test.Split(new String[] { String.Empty }, StringSplitOptions.None);
By the way: Possible Clone of this answer
Why does "abcd".StartsWith("") return true?
Do you really need to split the string, or are you just trying to get all the individual characters?
If so, then a string is also a IEnumerable<char>, and you also have an indexer.
So, what are you actually trying to do?
And no, you can't call the split methods with string.Empty or similar constructs.
string emptyString = string.Empty;
char[] emptyStringCharArr = emptyString.ToCharArray();
This will give you an empty array of chars.
This is because String is already an array of chars in memory, and String.Empty has no value.
To break it down further, consider an implementation of .ToCharArray()
private Char[] toCharArray(String value)
{
var stringLength = value.Length;
var returningArray = new char[stringLength];
for(var i = 0; i < stringLength; i++)
{
returningArray[i] = value[i];
}
return returningArray;
}
Length of course will be zero, and you will return an empty char array. Of course this isn't the exact implementation, but you can see how and why it's returning nothing (and therefore isn't splitting on the string as you're expecting it to)
It's not an array with a single element String.Empty, because that doesn't really make sense. When you try to split on an empty array, it doesn't know how or what to split on, so you're given back the original string.
As for why it returns 0 by default, consider:
private int IndexOf(String value, String searchFor)
{
for(var i = 0; i < value.Length; i++)
{
if(value.Substring(i, searchFor.Length) == searchFor)
{
return i;
}
}
return -1;
}
private int LastIndexOf(String value, String searchFor)
{
var searchLength = searchFor.Length;
for(var i = value.Length - searchFor.Length; i >= 0; i--)
{
if(value.Substring(i, searchLength) == searchFor)
return i;
}
return -1;
}
String.SubString(x, 0) will ALWAYS return String.Empty, regardless of what's passed in (even String.Empty). For this reason it's much faster to add a check and return 0 regardless (as it would even if it ran the loop).
Since String.Empty is just an empty string, so if you do:
var s = "part1" + string.Empty + "part2";
this will result in exactly the same string as:
var s = "part1" + "part2";
the first syntax will not insert a magic empty string between the two parts.
That IndexOf returns 0, is by definition, not because there is some magic empty string between characters.
I cannot think of a logic way to split a string, by an empty string. What should it return? When using an empty string as an argument to the string.Split method, it will be ignored. If it was the only separator to use, the string will be returned unsplit.
you could also say
"testing" == string.Empty + string.Empty + string.Empty + ... + "t" + string.Empty + string.empty + "esting";
So actually you could place an endless array of string.empty between each character.
So I think
1 not possible
2 none, it just doens't make sense...