I use Substring to decode a generated code for activating
but when a user enter wrong code like 1 or 123
c# stop and say "Index and length must refer to a location within the string." or ..
how to ignore it without check length ...
in php we can ignore warnings and error by using "#"
#myfunc(12);
but how in C# ?
The short answer is, you can't.
The correct answer is you shouldn't, and to check that the input is valid.
The horrible answer would look something like this:
public void SwallowExceptions(Action action)
{
try
{
action();
}
catch
{
}
}
public string DoSomething()
{
string data = "TerribleIdea";
string result = null;
SwallowExceptions(() => result = data.Substring(0, 10000));
return result;
}
Related
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.
Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.
Here's the function I am using:
#functions
{
public static class TextConvert
{
public static string ToTitleCase(string s)
{
s = s.ToLower();
return Regex.Replace(s, #"(^\w)|(\s\w)",b => b.Value.ToUpper());
}
}
}
How can I do that, accounting for cases like O'Reilly?
You can try It.
var titlecase = PrintName("o'riley");
Call this function
Public static string PrintName(string StrValue)//pass here - o'riley
{
if (!string.IsNullOrEmpty(StrValue))
{
return Regex.Replace(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(StrValue.ToLower()),
"['-](?:.)", m => m.Value.ToUpperInvariant());
}
else
{
return "Something meaningful message";
}
}
You can't do this with technical tools alone. There are African names that do not start with a capital letter at all. As you can see in this utility (http://www.johncardinal.com/tmgutil/capitalizenames.htm), the easiest way out is to actually maintain a list of exceptions and match your name against it.
I am new to C# and I'm trying to write a contains statement. I want the process to read the test variable and if it contains the word error then print the variable if it does not contain an error then print no error. I think my process is close except when I run the code below I get an error when the CLI runs.
"object reference not set to an instance of an object"
Any help would be appreciated!
while (true)
{
test = queue.GetMessage();
if (test.AsString.Contains("error"))
{
Console.WriteLine(string.Format("Variable: {0}", test.AsString));
}
else
Console.WriteLine(string.Format("No Error: {0}", test.AsString));
}
var message = queue.GetMessage()?? string.Empty;
var formattedMessage =
String.Format(
(message.IndexOf("error", StringComparison.OrdinalIgnoreCase) >= 0)
? "No Error: {0}"
: "Variable: {0}", message);
Console.WriteLine(formattedMessage);
Useful references:
Unique ways to use the Null Coalescing operator
Simplify conditional string format
If queue.GetMessage() return a string, then you don't need AsString. If you want to convert it to a string, override ToString().
while (true) {
test = queue.GetMessage();
if (test.ToString().Contains("error")) {
...
} else {
...
}
}
You can always guarantee that ToString() will be present because it's defined in the object base class. Just be sure it returns something intelligible, because default implementations may not.
I am working on a simple windows forms application that the user enters a string with delimiters and I parse the string and only get the variables out of the string.
So for example if the user enters:
2X + 5Y + z^3
I extract the values 2,5 and 3 from the "equation" and simply add them together.
This is how I get the integer values from a string.
int thirdValue
string temp;
temp = Regex.Match(variables[3], #"\d+").Value
thirdValue = int.Parse(temp);
variables is just an array of strings I use to store strings after parsing.
However, I get the following error when I run the application:
Input string was not in a correct format
Why i everyone moaning about this question and marking it down? it's incredibly easy to explain what is happening and the questioner was right to say it as he did. There is nothing wrong whatsoever.
Regex.Match(variables[3], #"\d+").Value
throws a Input string was not in a correct format.. FormatException if the string (here it's variables[3]) doesn't contain any numbers. It also does it if it can't access variables[3] within the memory stack of an Array when running as a service. I SUSPECT THIS IS A BUG The error is that the .Value is empty and the .Match failed.
Now quite honestly this is a feature masquerading as a bug if you ask me, but it's meant to be a design feature. The right way (IMHO) to have done this method would be to return a blank string. But they don't they throw a FormatException. Go figure. It is for this reason you were advised by astef to not even bother with Regex because it throws exceptions and is confusing. But he got marked down too!
The way round it is to use this simple additional method they also made
if (Regex.IsMatch(variables[3], #"\d+")){
temp = Regex.Match(variables[3], #"\d+").Value
}
If this still doesn't work for you you cannot use Regex for this. I have seen in a c# service that this doesn't work and throws incorrect errors. So I had to stop using Regex
I prefer simple and lightweight solutions without Regex:
static class Program
{
static void Main()
{
Console.WriteLine("2X + 65Y + z^3".GetNumbersFromString().Sum());
Console.ReadLine();
}
static IEnumerable<int> GetNumbersFromString(this string input)
{
StringBuilder number = new StringBuilder();
foreach (char ch in input)
{
if (char.IsDigit(ch))
number.Append(ch);
else if (number.Length > 0)
{
yield return int.Parse(number.ToString());
number.Clear();
}
}
yield return int.Parse(number.ToString());
}
}
you can change the string to char array and check if its a digit and count them up.
string temp = textBox1.Text;
char[] arra = temp.ToCharArray();
int total = 0;
foreach (char t in arra)
{
if (char.IsDigit(t))
{
total += int.Parse(t + "");
}
}
textBox1.Text = total.ToString();
This should solve your problem:
string temp;
temp = Regex.Matches(textBox1.Text, #"\d+", RegexOptions.IgnoreCase)[2].Value;
int thirdValue = int.Parse(temp);
I've got a with 1.1 build system here using Parse for converting values (now it's 3.5).
string myString = String.Empty;
double myValue = double.Parse(myString);
throws a FormatException (I expected 0.0).
If I rewrite that using 2.0+
string myString = String.Empty;
double myValue;
if (double.TryParse(myString, out myValue))
//do something
I get the wanted 0.0, but unfortunately I lose the possibility to get a meaningful error message (in the else tree).
Why is giving me Parse an error and TryParse my expected value?
Is there any way to get the error message out of TryParse (time is not the problem)?
I don't want to work around it like that:
Avoid the error using if...then
myValue = myString.Length == 0 ? 0.0 : double.Parse(myString);
Two Calls if an error occured
if (!double.TryParse(myString, out myValue))
myValue = double.Parse(myString);
Parse throws an exception if the string cannot be be parsed and TryParse returns a bool. You can handle this bool (true if the parsing was successful, else false) to display the success/error message you want to show.
Since myValue is an out parameter it has to be set by the method so, if the string cannot be parsed, TryParse sets it as 0.0 which is why you're getting that number when using the TryParse method.
No, it is not possible to get the exact error message. You only want to know if it is possible to convert to double and the result, if it is possible. The exact reason why the conversion fails is hidden from you.
TryParse allows you to convert without throwing exception and returns true if successful. The action you take depends on you
if (!double.TryParse(myString, out myValue))
{
//throw exception here
}
It is useful when you are not sure if input will always be numbers
Why is giving me Parse an error and TryParse my expected value?
Because that's the way the interface is designed. TryParse does not throw an exception if the input has an invalid format. Instead it returns false.
Is there any way to get the error message out of TryParse (time is not the problem)?
No, but you can make your own error message.
if (double.TryParse(myString, out myValue))
{
//do something
}
else
{
throw new FooException("Problem!");
}
But if you want to throw an exception when there is an error it's simpler to just use Parse.
TryParse is implemented somehow like this:
try
{
Parse(...);
return true;
}
catch
{
return false;
}
So you can do it just the same way:
try
{
double.Parse(str, out dbl);
}
catch (Exception ex)
{
// Do something with ex.Message
dbl = 0.0;
}
// Continue with dbl.
Forget double.TryParse, as it won't tell you (by design) why the parsing failed. Do it The Old Way:
string myString = String.Empty;
double myValue = 0.0;
try
{
myValue = double.Parse(myString);
}
catch (FormatException)
{
// Now you have a meaningful story here!
}
Out parameters has to be set, therefore if TryParse fails it will initialize the output to it's default before it returns, however you will and in the "else" loop... Meaning it failed...
Try running the code below, that will show you that TryParse actually overwrites the value, yet indicates that the parse fails...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ParseAndOutput("");
ParseAndOutput("1.0");
ParseAndOutput("ABC");
}
private static void ParseAndOutput(string input)
{
double value = -1;
if (double.TryParse(input, out value))
{
Console.WriteLine("Parse succeeded for '"+input+"', try parse changed to: " + value);
}
else
{
Console.WriteLine("Parse failed for '" + input + "', try parse changed to: " + value);
}
}
}
}
So both Parse and TryParse fails on string.Empty, they just report that failure differently which is the whole point of TryParse, it is never meant to throw an exception...
i am trying to make a simple application in C# in which every character I type is displayed in a console window. Here is my code :
class Program {
static void Main(string[] args) {
while (true) {
System.ConsoleKeyInfo input;
input = Console.ReadKey(false);
String d = input.ToString();
char c = d[0];
Console.WriteLine(c);
}
}
}
The problem is that the characters are not displayed correctly, and to be more precise, every character is followed by an 'S'. For example i type 'a' and i get 'aS' instead of 'a'. Any solutions? Thnx in advance!
What you are seeing is the following:
The original character you entered, since you passed false not true to ReadKey
The first characters of the string "System.ConsoleKeyInfo", since the ToString() method returns the typename (here), not the character entered.
Use the following code instead to achieve what you attempted:
while(true)
{
ConsoleKeyInfo info = Console.ReadKey(true);
Console.WriteLine(info.KeyChar);
}
Because input.ToString() == "System.ConsoleKeyInfo" :-)
Depending on what you want to do, try writing input.KeyChar.
The parameter of Console.ReadKey(false); defines if the key you type is intercepted or not. So Console.ReadKey(false); prints the character you type and Console.Writeline(c) prints the S.
Try char c = input.KeyChar; instead.
The problem is that you are using ToString() on a System.ConsoleKeyInfo. When this is turned into a string you will get "System.ConsoleKeyInfo" and the first character is therefore 'S'. Did you mean to write the following code instead?
while (true)
{
var input = Console.ReadKey(false);
Console.WriteLine(input.KeyChar);
}
With that code each character will get duplicated (so you will get aabbccddee). Change the false to true in ReadKey to fix that.