STRING: how to get string output from this input string? - c#

How do you get the message from the following inputs
Input is formated by field name separated by comma, followed by a colon, space and then the error message.
<FieldName1>, <FieldName2>, <FieldName3>: <ErrorMessage>"
Input Example
"ConsumerSecret, ConsumerKey: Invalid application credentials"
"Password: Invalid Must contain at least one alpha, one numeric, and one special character"
Method
string Message GetErrorByField (string FieldName, string InputString);
1
ErrorMessage = GetErrorByField("ConsumerSecret", "ConsumerSecret, ConsumerKey: Invalid application credentials");
ErrorMessage should now equal
"Invalid application credentials".
2
ErrorMessage = GetErrorByField("ConsumerKey", "ConsumerSecret, ConsumerKey: Invalid application credentials");
ErrorMessage should now equal
"Invalid application credentials".
3
ErrorMessage = GetErrorByField("Password", "Password: Invalid Must contain at least one alpha, one numeric, and one special character");
ErrorMessage should now equal
"Invalid Must contain at least one alpha, one numeric, and one special character".

Split the InputString i.e., second parameter in GetErrorByField() method by : then you will get the result by considering the splitted string with index 1
string Message = InputString.Split(':')[1].Trim();

You can simply use the Split method of the string class, and get the appropriate value:
GetErrorByField(string str)
{
var splited = str.Split(":".ToCharArray());
if (splited != null && splited.Length == 2)
return splited[1].TrimStart().TrimEnd();
return string.Empty;
}

Related

Input string 'x' is not a valid number error with JsonConvertDeserializeObject

I have a string for billingpostalcode. When you enter pure numbers on it ex: '12345' then it is working fine. But for example you put '123aa' or 'abcde' it is producing an exception. It is a string and not an integer so i don't understand the error.
{"Unexpected character encountered while parsing number: s. Path 'billingPostalCode', line 1, position 119."}
string billingPostal = billingPostalCode;
var obj = JsonConvert.DeserializeObject($"{{ 'odrDetailHdr' : {orderDetailHeaderJson}, 'billingPostalCode' : {billingPostal}, 'odrProductList': {orderTrackingDetailsProductJson}, 'odrDetailOtherHdr': {orderDetailOtherHeaderJson} }}");
Anyone has an idea why?
There is different notation between a string and a number in the json format.
"employee":{ "name":"John", "age":30, "city":"New York" }
Notice the difference between the string "name":"John"and the number "age":30, They are not interchangeable
However, in your example you could add the quotes, or use a converter via an attribute when using json.net

What does Console.ReadLine() do in this code context?

What is specific purpose of console.readline in this code?
String username = Console.Readline();
String password = Console.Readline();
String Valid = (username = "Kmp" && password = "Kmp")? "Valid user": "Invalid User";
Console.Writeline(Valid);
I am noob player ;), i need your help as much as you can give.
The code above is partially invalid. To address your primary question, Console.ReadLine() will read input from a user in the console window.
string username = Console.ReadLine();
username will be a memory reference of the user input. Also the type defined is as follows:
A string is a sequential collection of characters that is used to
represent text. A String object is a sequential collection of
System.Char objects that represent a string; a System.Char object
corresponds to a UTF-16 code unit. The value of the String object is
the content of the sequential collection of System.Char objects, and
that value is immutable (that is, it is read-only). For more
information about the immutability of strings, see the Immutability
and the StringBuilder class section later in this topic. The maximum
size of a String object in memory is 2GB, or about 1 billion
characters.
Now to address this logic:
String Valid = (username = "Kmp" && password = "Kmp")? "Valid user": "Invalid User";
You have a big issue in that line.
You do not use == which is for equality comparison.
I would likely do the following:
public string Authenticate(string username, string password)
{
if(String.Compare(username, "Example", false) == 0 && String.Compare(password, "Example", false) == 0)
return "Authenticated.";
return "Invalid credentials.";
}
Then where you have Valid you would simply have: string valid = Authenticate(username, password);. But instead of returning a string and consuming a message you could write back to the user directly with Write or WriteLine.
Other conditional approaches you could have done:
(username == "..." && password == "...") ? "..." : "..."
if(username == "..." && password == "...")
{
// True
}
Several approaches, but remember to use == for equality, single is for assigning values.
Console.ReadLine() is used to read input from console store input into string.
Here in your code, username and password is reading from console and storing it into respective variables
String username = Console.Readline(); //Reads input from console and store string value to username variable
String password = Console.Readline(); //Reads input from console and store string value to password variable
From MSDN
Reads the next line of characters from the standard input stream.
Console.ReadLine Method

Read input with different datatypes and space seperation

I'm trying to figure out how to write code to let the user input three values (string, int, int) in one line with space to separate the values.
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
How can I do it with different datatypes?
For example:
The user might want to input
Hello 23 54
I'm using console application C#
Well the first problem is that you need to decide whether the text the user enters itself can contain spaces. For example, is the following allowed?
Hello World, it's me 08 15
In that case, String.Split will not really be helpful.
What I'd try is using a regular expression. The following may serve as a starting point:
Match m = Regex.Match(input, #"^(?<text>.+) (?<num1>(\+|\-)?\d+) (?<num2>(\+|\-)?\d+)$");
if (m.Success)
{
string stringValue = m.Groups["text"].Value;
int num1 = Convert.ToInt32(m.Groups["num1"].Value);
int num2 = Convert.ToInt32(m.Groups["num2"].Value);
}
BTW: The following part of your question makes me frown:
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
A string is always just a string. Whether it contains a text, your email-address or your bank account balance. It is always just a series of characters. The notion that the string contains a number is just your interpretation!
So from a program's point of view, the string you gave is a series of characters. And for splitting that it doesn't matter at all what the real semantics of the content are.
That's why the splitting part is separate from the conversion part. You need to tell your application that that the first part is a string, the second and third parts however are supposed to be numbers. That's what you need type conversions for.
You are confusing things. A string is either null, empty or contains a sequence of characters. It never contains other data types. However, it might contain parts that could be interpreted as numbers, dates, colors etc... (but they are still strings). "123" is not an int! It is a string containing a number.
In order to extract these pieces you need to do two things:
Split the string into several string parts.
Convert string parts that are supposed to represent whole numbers into a the int type (=System.Int32).
string input = "Abc 123 456"
string[] parts = input.Split(); //Whitespaces are assumed as separators by default.
if (parts.Count == 3) {
Console.WriteLine("The text is \"{0}\"", parts[0]);
int n1;
if (Int32.TryParse(parts[1], out n1)) {
Console.WriteLine("The 1st number is {0}", n1);
} else {
Console.WriteLine("The second part is supposed to be a whole number.");
}
int n2;
if (Int32.TryParse(parts[2], out n2)) {
Console.WriteLine("The 2nd number is {0}", n2);
} else {
Console.WriteLine("The third part is supposed to be a whole number.");
}
} else {
Console.WriteLine("You must enter three parts separated by a space.");
}
What you have to do is get "Hello 23 54" in a string variable. Split by " " and treat them.
string value = "Hello 23 54";
var listValues = value.Split(' ').ToList();
After that you have to parse each item from listValues to your related types.
Hope it helps. ;)

Convert emailaddress to valid path

I created an winforms application, which creates a small SQLite database for every user. The database name contains the e-mailaddress of the user.
Scenario:
a user with e-mailaddress: test#test.com
uses the application, the following database will be created:
test#test.com.sqlite
I know that there are scenario's that the e-mailaddress converted to a path, will not be converted to a valid path.
the following characters are reserved by path: / \ ? % * : | " < > . and a space
I'm currently using the next method to filter the e-mailaddress:
public string ReturnFilteredUsername(string username)
{
username = username.Replace("<", "x"); username = username.Replace(">", "x"); username = username.Replace(":", "x"); username = username.Replace("\"", "x");
username = username.Replace("/", "x"); username = username.Replace(#"\", "x"); username = username.Replace("|", "x"); username = username.Replace("?", "x");
username = username.Replace("*", "x");
return username;
}
All reserved characters get replaced by an "x" at the moment, I want to convert all invalid characters to "%20". It is possible for me to just replace the "x" with "%20", but I don't think that's a 'clean' method
Can somebody come up with a more 'clean' method?
Thanks in advance!
Rather than using the user's email to name the database, identify each user by a numeric ID, and use that to name the databases.
In addition to always being valid as a file name, this allows users to change their email address without you having to worry about still pointing to the correct database.
Alternately, if you're set on using email addresses for the names, see this answer about which characters are valid in an email address. As long as all of the email address are valid, you only need to worry about escaping those characters that are both valid for emails and invalid for path.
I'd suggest either using a valid-for-path and invalid-for-email character to start an escape sequence (different sequence for each character you'll have to escape), or selecting a less common character valid for both, and using that as an escape character (remembering to escape it as well!).
Example:
Both % and ? are listed as valid for emails and invalid for paths. Assuming we use & to escape (valid for both!), we would create a mapping like this:
"&" = &00;
"%" = &01;
"?" = &02;
You would go through each email address and replace each occurence of invalid characters with their escaped equivalent, making it both as unique as the email address and safe as a path anme.
"a&b?100%#example.com" would becomee "a&00;b&02;100&01;#example.com".

Remove formatting from a string: "(123) 456-7890" => "1234567890"?

I have a string when a telephone number is inputted - there is a mask so it always looks like "(123) 456-7890" - I'd like to take the formatting out before saving it to the DB.
How can I do that?
One possibility using linq is:
string justDigits = new string(s.Where(c => char.IsDigit(c)).ToArray());
Adding the cleaner/shorter version thanks to craigmoliver
string justDigits = new string(s.Where(char.IsDigit).ToArray())
You can use a regular expression to remove all non-digit characters:
string phoneNumber = "(123) 456-7890";
phoneNumber = Regex.Replace(phoneNumber, #"[^\d]", "");
Then further on - depending on your requirements - you can either store the number as a string or as an integer. To convert the number to an integer type you will have the following options:
// throws if phoneNumber is null or cannot be parsed
long number = Int64.Parse(phoneNumber, NumberStyles.Integer, CultureInfo.InvariantCulture);
// same as Int64.Parse, but returns 0 if phoneNumber is null
number = Convert.ToInt64(phoneNumber);
// does not throw, but returns true on success
if (Int64.TryParse(phoneNumber, NumberStyles.Integer,
CultureInfo.InvariantCulture, out number))
{
// parse was successful
}
Since nobody did a for loop.
long GetPhoneNumber(string PhoneNumberText)
{
// Returns 0 on error
StringBuilder TempPhoneNumber = new StringBuilder(PhoneNumberText.Length);
for (int i=0;i<PhoneNumberText.Length;i++)
{
if (!char.IsDigit(PhoneNumberText[i]))
continue;
TempPhoneNumber.Append(PhoneNumberText[i]);
}
PhoneNumberText = TempPhoneNumber.ToString();
if (PhoneNumberText.Length == 0)
return 0;// No point trying to parse nothing
long PhoneNumber = 0;
if(!long.TryParse(PhoneNumberText,out PhoneNumber))
return 0; // Failed to parse string
return PhoneNumber;
}
used like this:
long phoneNumber = GetPhoneNumber("(123) 456-7890");
Update
As pr commented many countries do have zero's in the begining of the number, if you need to support that, then you have to return a string not a long. To change my code to do that do the following:
1) Change function return type from long to string.
2) Make the function return null instead of 0 on error
3) On successfull parse make it return PhoneNumberText
You can make it work for that number with the addition of a simple regex replacement, but I'd look out for higher initial digits. For example, (876) 543-2019 will overflow an integer variable.
string digits = Regex.Replace(formatted, #"\D", String.Empty, RegexOptions.Compiled);
Aside from all of the other correct answers, storing phone numbers as integers or otherwise stripping out formatting might be a bad idea.
Here are a couple considerations:
Users may provide international phone numbers that don't fit your expectations. See these examples So the usual groupings for standard US numbers wouldn't fit.
Users may NEED to provide an extension, eg (555) 555-5555 ext#343 The # key is actually on the dialer/phone, but can't be encoded in an integer. Users may also need to supply the * key.
Some devices allow you to insert pauses (usually with the character P), which may be necessary for extensions or menu systems, or dialing into certain phone systems (eg, overseas). These also can't be encoded as integers.
[EDIT]
It might be a good idea to store both an integer version and a string version in the database. Also, when storing strings, you could reduce all punctuation to whitespace using one of the methods noted above. A regular expression for this might be:
// (222) 222-2222 ext# 333 -> 222 222 2222 # 333
phoneString = Regex.Replace(phoneString, #"[^\d#*P]", " ");
// (222) 222-2222 ext# 333 -> 2222222222333 (information lost)
phoneNumber = Regex.Replace(phoneString, #"[^\d]", "");
// you could try to avoid losing "ext" strings as in (222) 222-2222 ext.333 thus:
phoneString = Regex.Replace(phoneString, #"ex\w+", "#");
phoneString = Regex.Replace(phoneString, #"[^\d#*P]", " ");
Try this:
string s = "(123) 456-7890";
UInt64 i = UInt64.Parse(
s.Replace("(","")
.Replace(")","")
.Replace(" ","")
.Replace("-",""));
You should be safe with this since the input is masked.
You could use a regular expression or you could loop over each character and use char.IsNumber function.
You would be better off using regular expressions. An int by definition is just a number, but you desire the formatting characters to make it a phone number, which is a string.
There are numerous posts about phone number validation, see A comprehensive regex for phone number validation for starters.
As many answers already mention, you need to strip out the non-digit characters first before trying to parse the number. You can do this using a regular expression.
Regex.Replace("(123) 456-7890", #"\D", String.Empty) // "1234567890"
However, note that the largest positive value int can hold is 2,147,483,647 so any number with an area code greater than 214 would cause an overflow. You're better off using long in this situation.
Leading zeros won't be a problem for North American numbers, as area codes cannot start with a zero or a one.
Alternative using Linq:
string phoneNumber = "(403) 259-7898";
var phoneStr = new string(phoneNumber.Where(i=> i >= 48 && i <= 57).ToArray());
This is basically a special case of C#: Removing common invalid characters from a string: improve this algorithm. Where your formatng incl. White space are treated as "bad characters"
'you can use module / inside sub main form VB.net
Public Function ClearFormat(ByVal Strinput As String) As String
Dim hasil As String
Dim Hrf As Char
For i = 0 To Strinput.Length - 1
Hrf = Strinput.Substring(i, 1)
If IsNumeric(Hrf) Then
hasil &= Hrf
End If
Next
Return Strinput
End Function
'you can call this function like this
' Phone= ClearFormat(Phone)
public static string DigitsOnly(this string phoneNumber)
{
return new string(
new[]
{
// phoneNumber[0], (
phoneNumber[1], // 6
phoneNumber[2], // 1
phoneNumber[3], // 7
// phoneNumber[4], )
// phoneNumber[5],
phoneNumber[6], // 8
phoneNumber[7], // 6
phoneNumber[8], // 7
// phoneNumber[9], -
phoneNumber[10], // 5
phoneNumber[11], // 3
phoneNumber[12], // 0
phoneNumber[13] // 9
});
}

Categories

Resources