Converting unicode characters (C#) Testing - c#

I have the following problem
I am using an SDK that returns values form a database.
The value i need is 4, 6, 7 but the SDK returns "\u0004","\u0006","\u0007" I was wondering if there is a way to check if it is "\u0004","\u0006","\u0007" or any way of doing this?
I Have the following code (C#):
Line_Type = Line_Type.Replace(#"\u000", "");
if (Line_Type == "4")
{
Line_Type = "4";
}
else if (Line_Type == "6")
{
Line_Type = "6";
}
else if (Line_Type == "7")
{
Line_Type = "7";
}
I have tried multiple ways to get the done but can't find a right way to get this done.
I Have google but can't find anything.

From your question I understood that SDK returns values in unicoded style.
Then you can use the following code to convert unicode values to respective decimal value.
char uniCodeValue = char.Parse(Line_Type);// '\u0004' unicode values
int decimalValue = uniCodeValue;
Console.Write(decimalValue.ToString()); // prints 4
Hope your problem got solved!!

In your replace call, "\u" is considered as an escape char. if you use double \, you get the string "\u0009";
check the difference between these two:
Console.WriteLine ("\u0009");
Console.WriteLine ("\\u0009");
the second print the string you are trying to replace with an empty string.

Related

How to check if a textbox starts with numeric value

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:
if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
richTextBox1.Text.Insert(0, "-");
}
So I was asking, if there's a shorter way to replace that code?
if (Char.IsNumber(richTextBox1.Text[0]))...
You should also add some checks around it to make sure there's text.
Using regex:
if (Regex.IsMatch(richTextBox1.Text, #"^\d"))
Matches a digit (0-9) at the start of the string.
Or a direct replace:
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\d", "-$&");
Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:
if ( Char.IsNumber( stringInput, 0) ) {
// String input begins with a number
}
More information:
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber
Many good answer's already here, another alternative is if you want culture support give this a try...
public static bool IsNumber(char character)
{
try
{
int.Parse(character.ToString(), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException) { return false; }
}
You can call it like:
if ( IsNumber(richTextBox1.Text[0]))

Verify empty field Selenium C#

I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}

Java Character.MATH_SYMBOL to C# conversion

.NET 4.6.1 C#
I found a possible solution to a problem I'm having. The solution is written in Java. I converted 99% of it to C# easily, sans 1 line. Here's the synopsis.
They have a string that is converted to a character array. Here's the C# equivalent:
string pFormula = "my string";
char[] tokens = pFormula.ToCharArray();
Then the following line of code occurs (this is Java):
if (Character.getType(tokens[i]) == Character.MATH_SYMBOL){
//do something
}
This is where i'm stuck. I can do this:
tokens[i].GetType() //Character.getType(tokens[i])
Does anyone know the C# equivalent of java's Character.MATH_SYMBOL? Thanks
char plus = '+';
if(char.GetUnicodeCategory(plus) == UnicodeCategory.MathSymbol)
{
//return true
}
You need to use UnicodeCategory
Be aware not every symbol which can be used in Math is in UnicodeCategory.MathSymbol. * and / are not part of MathSybols
char a2 = '*';
if(char.GetUnicodeCategory(a2) == UnicodeCategory.OtherPunctuation)
{
//return true, but return false for Math.
}
Here how it looks like the unicode character for multiplication and division used in MathSymbols.
char multiplication = '×';
char division = '÷';
Here this should be List of characters in unicode designation Sm(symbol,math)

Complex string compare logic

I need help with some complex (for me anyway as I not too experienced) string comparison logic. Basically, I want to validate a string to make sure it matches a format rule. I am using C#, targeting .NET 4.5.2.
I am trying to work with an API which gives me the expected format of the string this way:
1:420+4:9#### (must have “420” starting in position 1 AND have a “9” in position 4 AND have numeric digits in positions 5-8
2:Z+14:&&+20:10,11,12 (must have a “Z” in position 2 AND and alpha letters in positions 14, 15 AND have either “10”, “11”, or “12” starting in position 20
Legend:
":" = position/valuelist separator
"," = value separator
"+" = test separator
"#" = numeric digit-only wildcard
"&" = alpha letter-only wildcard
Given this, my first thought is to do a series of substrings and splits of the input string and then do compare on each section? Or, I could do a for loop and iterate through each character one by one until I hit the end of the length of the input string.
Let's assume in this case that the input string is something like "420987435744585". Using rule number one, I should get a pass on this since the first three are 420, position 4 is a 9 and the next 5-8 are numeric.
So far, I have created a method that returns a bool if I pass/fail validation. The input string is passed in. I then started to split on + or - to get all of the and or not sections and then split on comma to get the groups of rules. But this is where I am stuck. It seems like it should be easy and maybe it is but I just can't seem to wrap my head around it and I am thinking I am going to end up with a ton of arrays, foreach loops, if statements, etc... Just to validate and return true/false if the input string matches my format.
Can somebody please assist and give some guidance?
Thank you!!!!
The best way to handle these conditions would be using Regular Expressions (Regex). At first, you may find it a bit complicated, but it's worth to put time on learning it to handle all types of string patterns in a simple non-verbose way.
You can start with these tutorials :
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial
http://www.tutorialspoint.com/csharp/csharp_regular_expressions.htm
And use this one as a reference :
https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
I think the best way is a custom function, it will be faster than RegEx, and it would be a lot of manual work to convert that format to RegEx.
I've made a start at the validation function, and it's testing ok for the samples you provided.
Here is the code:
static bool CheckFormat(string formatString, string value)
{
string[] tests = formatString.Split('+');
foreach(string test in tests)
{
string[] testElement = test.Split(':');
int startPos = int.Parse(testElement[0]);
string patterns = testElement[1];
string[] patternElements = patterns.Split(',');
foreach(string patternElement in patternElements)
{
//value string not long enough, so fail.
if(startPos + patternElement.Length > value.Length)
return false;
for (int i = 0; i < patternElement.Length; i++)
{
switch(patternElement[i])
{
case '#':
if (!Char.IsNumber(value[i]))
return false;
break;
case '&':
if (!Char.IsLetter(value[i]))
return false;
break;
default:
if(patternElement[i] != value[i])
return false;
break;
}
}
}
}
return true;
}
The dotnet fiddle is here if you want to play with it: https://dotnetfiddle.net/52olLQ.
Good luck.

Convert Unicode string made up of culture-specific digits to integer value

I am developing a program in the Marathi language. In it, I want to add/validate numbers entered in Marathi Unicode by getting their actual integer value.
For example, in Marathi:
४५ = 45
९९ = 99
How do I convert this Marathi string "४५" to its actual integer value i.e. 45?
I googled a lot, but found nothing useful. I tried using System.Text.Encoding.Unicode.GetString() to get string and then tried to parse, but failed here also.
Correct way would be to use Char.GetNumericValue that lets you to convert individual characters to corresponding numeric values and than construct complete value. I.e. Char.GetNumericValue('९') gives you 9.
Depending on your goal it may be easier to replace each national digit character with corresponding invariant digit and use regular parsing functions.
Int32.Parse("९९".Replace("९", "9"))
Quick hack of #Alexi's response.
public static double ParseValue(string value)
{
return double.Parse(string.Join("",
value.Select(c => "+-.".Contains(c)
? "" + c: "" + char.GetNumericValue(c)).ToArray()),
NumberFormatInfo.InvariantInfo);
}
calling ParseValue("१२३.३२१") yields 123.321 as result
I found my solution...
The following code will convert given Marathi number to its equivalent Latin number..
Thanks to #Alexei, I just changed some of your code and its working fine..
string ToLatinDigits(string nativeDigits)
{
int n = nativeDigits.Length;
StringBuilder latinDigits = new StringBuilder(capacity: n);
for (int i = 0; i < n; ++i)
{
if (char.IsDigit(nativeDigits, i))
{
latinDigits.Append(char.GetNumericValue(nativeDigits, i));
}
else if (nativeDigits[i].Equals('.') || nativeDigits[i].Equals('+') || nativeDigits[i].Equals('-'))
{
latinDigits.Append(nativeDigits[i]);
}
else
{
throw new Exception("Invalid Argument");
}
}
return latinDigits.ToString();
}
This method is working for both + and - numbers.
Regards Guruprasad
Windows.Globalization.DecimalFormatter will parse different numeral systems in addition to Latin, including Devanagari (which is what is used by Marathi).

Categories

Resources