C
C#2y ago
surwren

String Reversal

Geeksforgeeks' solution checks for str==null (which I presume is in case someone calls reverse()). My questions are as follows: 1. How many different ways can the actual terminating condition be called? I used (str == "") but it seems (str.Length <= 1) or (str.Length==0) can also be used. What are some others? What are the advantages/disadvantages of each? 2. Why doesn't Console.Write(str) where str is null call up an unhandled exception?
2 Replies
Pobiega
Pobiega2y ago
null converts to "" when printed there are many ways to check for an empty string. My personal favorite is string.IsNullOrEmpty(yourStringVariable)
Groophy
Groophy2y ago
public static string Reverse(string str)
{
return String.Concat((string.IsNullOrEmpty(str) ? "" : str).ToCharArray().Reverse());
}
public static string Reverse(string str)
{
return String.Concat((string.IsNullOrEmpty(str) ? "" : str).ToCharArray().Reverse());
}
better method
public static string Reverse(string str) => return String.Concat((string.IsNullOrEmpty(str) ? "" : str).ToCharArray().Reverse());
public static string Reverse(string str) => return String.Concat((string.IsNullOrEmpty(str) ? "" : str).ToCharArray().Reverse());
don't give error when null
Want results from more Discord servers?
Add your server
More Posts