C# convert XML Node string to Int32 - c#

I reading data from webservice and is not clean. I need to convert string to Int where string can be null, number or with white spaces. I make simple program to achieve this but with whitespaces my code does not hit ... If (uint.TryParse(cleanNumber, out ux)) not sure what I am missing from puzzle?
public class Program
{
static void Main(string[] args)
{
string no = "08709079777 ";
//string no = "0870777777";
Console.WriteLine("no "+ no);
Program o = new Program();
var t1 = o.ConvertStringToInt32(no);
Console.WriteLine("t1 "+ t1);
Console.ReadLine();
}
private int ConvertStringToInt32(string number)
{
int returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number, #"\s+", "");
uint ux;
if (uint.TryParse(cleanNumber, out ux))
{
returnIntVal = (int)ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
return returnIntVal;
}
}

The number 0870777777 you are trying to parse is beyond int data type range which is -2,147,483,648 to 2,147,483,647. Check the data type ranges at here.
Use the data type as long (or Int64).
private static long ConvertStringToInt32(string number)
{
long returnIntVal = 0;
try
{
if (!string.IsNullOrEmpty(number))
{
var cleanNumber = Regex.Replace(number, #"\s+", "");
if (long.TryParse(cleanNumber, out long ux))
{
returnIntVal = ux;
}
}
else
{
returnIntVal = 0;
}
}
catch(Exception exp)
{
var ex = exp;
}
Console.WriteLine("returnIntVal: " + returnIntVal);
return returnIntVal;
}
Check this fiddle - https://dotnetfiddle.net/3Luoon

Well i dont know why you complicate things but this should be really very easy to solve
public int ConvertToInt(string n) {
// Trim should solve your case where the number end or start with whitespace. but just
// incase i did the replace thing to if there is any whitespace between the numbers.
// So its upp to you if you want to retaine the replace or not.
n = n?.Replace(" ", "").Trim();
if (Int.TryParse(n, var out number))
return number;
else return 0;
}

Related

do-while loop does not go through while condition C#

I wrote a do-while loop but it does not run through while condition somehow.
When I type in invalid characters it should go back to beginning and repeat as it's supposed to.
I ran the code step by step on Visual Studio and it shows that code does not even go through while condition. (no matter what the input value is)
Can someone please help me?
Many thanks in advance!
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))==-1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
return inputCharacters;
} while (invalidCharacters != null);
}
}
}
The problem is that you return the inputed string at the end of the loop no matter the validation done.
You can use a boolean to check this validity.
Also you don't need to parse all the string and you can break the inner loop on the first invalid char.
I renamed the string as result to use a standard pattern and to be more clean.
For example:
static string GetUserString(string letters)
{
string result;
bool isValid;
do
{
Console.Write("Enter : ");
result = Console.ReadLine();
isValid = true;
foreach ( char c in result )
if ( letters.IndexOf(char.ToUpper(c)) == -1 )
{
isValid = false;
Console.WriteLine("Enter a valid input");
break;
}
}
while ( !isValid );
return result;
}
The line return inputCharacters; makes it leave the loop.
I think you meant:
} while (invalidCharacters != null);
return inputCharacters;
using System;
using static System.Console;
namespace a5
{
class Program
{
const string acceptedLetters = "EHLNTXZ";
static void Main(string[] args)
{
GetUserString(acceptedLetters);
ReadKey();
}
static string GetUserString(string letters)
{
string invalidCharacters;
do
{
invalidCharacters = null;
Write("Enter : ");
string inputCharacters = ReadLine();
foreach(char c in inputCharacters)
{
if(letters.IndexOf(char.ToUpper(c))== -1)
{
invalidCharacters = c.ToString();
}
}
if(invalidCharacters != null)
{
WriteLine("Enter a valid input");
}
} while (invalidCharacters != null);
return inputCharacters;
}
}
}

Random is not working good

I generate a string with 62 options ^ 6 letters = 56,800,235,584
But when running the code, it repeats the same string less then every 200,200 times
What is the problem here?
BTW:
This code is based on the answer here
class Program
{
static void Main(string[] args)
{
var d = new Dictionary<string, bool>();
for (int i = 0; ; i++)
{
var s = GenerateString(6);
try
{
d.Add(s, false);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("{0} - {1} - {2}", i, s, ex.Message));
i = 0;
}
}
Console.ReadKey();
}
static Random _rnd = new Random();
public static string GenerateString(int len)
{
const string bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string smallLetters = "abcdefghijklmnopqrstuvwxyz";
const string numbers = "1234567890";
var validChars = bigLetters + smallLetters + numbers;
var result = new StringBuilder();
for (int i = 0; i < len; i++)
{
result.Append(validChars[_rnd.Next(validChars.Length)]);
}
return result.ToString();
}
}
There is all OK with random.
The problem is related with Birthday paradox. When you have 200k items one of them could repeat.
Random string doesnt garantee always unique result. For unique results you should use GUID's.
To avoid repeatation you can do a check for existence before adding the string to the list:
After for loop in GenerateString()
if(d.Contains(result.ToString()) // check whether the current generated string is in the list
{
GenerateString(len); // if it is already existed generate another one
}
else
{
return result.ToString(); // if not then return the string
}

How to add exception for errors(try, catch)

This is my code for some console app. First thing that doesn't work very well is method SwitchLetters. When I input some string and press enter every letter goes to new line. I don't know why. Also i don't know how to display lower and upper case in methods PrintBeforeSwitch and PrintAfterSwitch. And Exception how to use try and catch for some exception and which exception to use...
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
ns.SwitchLetters(input);
so.PrintBeforeSwitch(input);
so.PrintAfterSwitch(input);
}
}
class NewString
{
private string newString;
public string _NewString
{
get
{
return newString;
}
set
{
newString = value;
}
}
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
Console.ReadLine();
Console.WriteLine(newStr.ToUpper());
}
}
}
class StringOperation
{
private string inputString;
//public NewString newSrt;
public string InputString
{
get
{
return inputString;
}
set
{
inputString = value;
}
}
public int VocalNumber(string str)
{
int num;
return num = str.Count(a => "aeiouAEIOU".Contains(a));
}
public int SpaceNumber(string str)
{
int num;
return num = str.Count(b => b == ' ');
}
public List<int> LowerUpperCaseLattersNumber(string str)
{
int counterLower = 0;
int counterUpper = 0;
List<int> counter = new List<int>();
foreach (char value in str)
{
if (char.IsLower(value))
{
counterLower++;
}
else
{
counterUpper++;
}
}
counter.Add(counterLower);
counter.Add(counterUpper);
Console.WriteLine("Number of small latters is: {0}", counterLower);
Console.WriteLine("Number of big letters is: {0}", counterUpper);
return counter;
}
public string SwitchVocals(ref string str)
{
string vocals = str.Replace("a", "x").Replace("e", "x").Replace("i", "x").Replace("o", "x").Replace("u", "x").Replace("A", "X").Replace("E", "X").Replace("I", "X").Replace("O", "X").Replace("U", "X");
Console.WriteLine(vocals);
return vocals;
}
public void PrintBeforeSwitch(string str)
{
Console.WriteLine(str);
Console.WriteLine("Information about string:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
public void PrintAfterSwitch(string str)
{
SwitchVocals(ref str);
Console.WriteLine("Information about string after switch:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
}
Here is an idea how to do the exception:
public void SwitchLetters(string newStr)
{
try
{
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();//this stops the program so you can read the error
}
}
I think you had the two lines swapped around so.PrintBeforeSwitch and ns.SwitchLetters
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
so.PrintBeforeSwitch(input);
ns.SwitchLetters(input);
so.PrintAfterSwitch(input);
}
If you use Console.WriteLine("some string here"); it will do exactly as it says, write line. However you can use Console.Write("some string here"); and it should add the text/string onto the existing line.
Can you please give us more information by what you mean "First thing that doesn't work very well is method SwitchLetters..." what should it do? What does it currently do?
To resolve your issue in the comment below remove the Console.ReadLine()
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
//Console.ReadLine(); This line needs to be removed
Console.WriteLine(newStr.ToUpper());
}
}

How to insert/remove hyphen to/from a plain string in c#?

I have a string like this;
string text = "6A7FEBFCCC51268FBFF";
And I have one method for which I want to insert the logic for appending the hyphen after 4 characters to 'text' variable. So, the output should be like this;
6A7F-EBFC-CC51-268F-BFF
Appending hyphen to above 'text' variable logic should be inside this method;
public void GetResultsWithHyphen
{
// append hyphen after 4 characters logic goes here
}
And I want also remove the hyphen from a given string such as 6A7F-EBFC-CC51-268F-BFF. So, removing hyphen from a string logic should be inside this method;
public void GetResultsWithOutHyphen
{
// Removing hyphen after 4 characters logic goes here
}
How can I do this in C# (for desktop app)?
What is the best way to do this?
Appreciate everyone's answer in advance.
GetResultsWithOutHyphen is easy (and should return a string instead of void
public string GetResultsWithOutHyphen(string input)
{
// Removing hyphen after 4 characters logic goes here
return input.Replace("-", "");
}
for GetResultsWithHyphen, there may be slicker ways to do it, but here's one way:
public string GetResultsWithHyphen(string input)
{
// append hyphen after 4 characters logic goes here
string output = "";
int start = 0;
while (start < input.Length)
{
output += input.Substring(start, Math.Min(4,input.Length - start)) + "-";
start += 4;
}
// remove the trailing dash
return output.Trim('-');
}
Use regex:
public String GetResultsWithHyphen(String inputString)
{
return Regex.Replace(inputString, #"(\w{4})(\w{4})(\w{4})(\w{4})(\w{3})",
#"$1-$2-$3-$4-$5");
}
and for removal:
public String GetResultsWithOutHyphen(String inputString)
{
return inputString.Replace("-", "");
}
Here's the shortest regex I could come up with. It will work on strings of any length. Note that the \B token will prevent it from matching at the end of a string, so you don't have to trim off an extra hyphen as with some answers above.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string text = "6A7FEBFCCC51268FBFF";
for (int i = 0; i <= text.Length;i++ )
Console.WriteLine(hyphenate(text.Substring(0, i)));
}
static string hyphenate(string s)
{
var re = new Regex(#"(\w{4}\B)");
return re.Replace (s, "$1-");
}
static string dehyphenate (string s)
{
return s.Replace("-", "");
}
}
}
var hyphenText = new string(
text
.SelectMany((i, ch) => i%4 == 3 && i != text.Length-1 ? new[]{ch, '-'} : new[]{ch})
.ToArray()
)
something along the lines of:
public string GetResultsWithHyphen(string inText)
{
var counter = 0;
var outString = string.Empty;
while (counter < inText.Length)
{
if (counter % 4 == 0)
outString = string.Format("{0}-{1}", outString, inText.Substring(counter, 1));
else
outString += inText.Substring(counter, 1);
counter++;
}
return outString;
}
This is rough code and may not be perfectly, syntactically correct
public static string GetResultsWithHyphen(string str) {
return Regex.Replace(str, "(.{4})", "$1-");
//if you don't want trailing -
//return Regex.Replace(str, "(.{4})(?!$)", "$1-");
}
public static string GetResultsWithOutHyphen(string str) {
//if you just want to remove the hyphens:
//return input.Replace("-", "");
//if you REALLY want to remove hyphens only if they occur after 4 places:
return Regex.Replace(str, "(.{4})-", "$1");
}
For removing:
String textHyphenRemoved=text.Replace('-',''); should remove all of the hyphens
for adding
StringBuilder strBuilder = new StringBuilder();
int startPos = 0;
for (int i = 0; i < text.Length / 4; i++)
{
startPos = i * 4;
strBuilder.Append(text.Substring(startPos,4));
//if it isn't the end of the string add a hyphen
if(text.Length-startPos!=4)
strBuilder.Append("-");
}
//add what is left
strBuilder.Append(text.Substring(startPos, 4));
string textWithHyphens = strBuilder.ToString();
Do note that my adding code is untested.
GetResultsWithOutHyphen method
public string GetResultsWithOutHyphen(string input)
{
return input.Replace("-", "");
}
GetResultsWithOutHyphen method
You could pass a variable instead of four for flexibility.
public string GetResultsWithHyphen(string input)
{
string output = "";
int start = 0;
while (start < input.Length)
{
char bla = input[start];
output += bla;
start += 1;
if (start % 4 == 0)
{
output += "-";
}
}
return output;
}
This worked for me when I had a value for a social security number (123456789) and needed it to display as (123-45-6789) in a listbox.
ListBox1.Items.Add("SS Number : " & vbTab & Format(SSNArray(i), "###-##-####"))
In this case I had an array of Social Security Numbers. This line of code alters the formatting to put a hyphen in.
Callee
public static void Main()
{
var text = new Text("THISisJUSTanEXAMPLEtext");
var convertText = text.Convert();
Console.WriteLine(convertText);
}
Caller
public class Text
{
private string _text;
private int _jumpNo = 4;
public Text(string text)
{
_text = text;
}
public Text(string text, int jumpNo)
{
_text = text;
_jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
}
public string Convert()
{
if (string.IsNullOrEmpty(_text))
{
return string.Empty;
}
if (_text.Length < _jumpNo)
{
return _text;
}
var convertText = _text.Substring(0, _jumpNo);
int start = _jumpNo;
while (start < _text.Length)
{
convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
start += _jumpNo;
}
return convertText;
}
}

How to extract phrases and then words in a string of text?

I have a search method that takes in a user-entered string, splits it at each space character and then proceeds to find matches based on the list of separated terms:
string[] terms = searchTerms.ToLower().Trim().Split( ' ' );
Now I have been given a further requirement: to be able to search for phrases via double quote delimiters a la Google. So if the search terms provided were:
"a line of" text
The search would match occurrences of "a line of" and "text" rather than the four separate terms [the open and closing double quotes would also need to be removed before searching].
How can I achieve this in C#? I would assume regular expressions would be the way to go, but haven't dabbled in them much so don't know if they are the best solution.
If you need any more info, please ask. Thanks in advance for the help.
Here's a regex pattern that would return matches in groups named 'term':
("(?<term>[^"]+)"\s*|(?<term>[^ ]+)\s*)+
So for the input:
"a line" of text
The output items identified by the 'term' group would be:
a line
of
text
Regular expressions would definitely be the way to go...
You should check this MSDN link out for some info on the Regex class:
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
and here is an excellent link to learn some regular expression syntax:
http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx
Then to add some code examples, you could be doing it something along these lines:
string searchString = "a line of";
Match m = Regex.Match(textToSearch, searchString);
or if you just want to find out if the string contains a match or not:
bool success = Regex.Match(textToSearch, searchString).Success;
use the regular expression builder here
http://gskinner.com/RegExr/
and you will be able to manipulate the regular expression to how you need it displayed
Use Regexs....
string textToSearchIn = ""a line of" text";
string result = Regex.Match(textToSearchIn, "(?<=").*?(?=")").Value;
or if more then one, put this into a match collection...
MatchCollection allPhrases = Regex.Matches(textToSearchIn, "(?<=").*?(?=")");
The Knuth-Morris-Pratt (KMP algorithm)is recognised as the fastest algorithm for finding substrings in strings (well, technically not strings but byte-arrays).
using System.Collections.Generic;
namespace KMPSearch
{
public class KMPSearch
{
public static int NORESULT = -1;
private string _needle;
private string _haystack;
private int[] _jumpTable;
public KMPSearch(string haystack, string needle)
{
Haystack = haystack;
Needle = needle;
}
public void ComputeJumpTable()
{
//Fix if we are looking for just one character...
if (Needle.Length == 1)
{
JumpTable = new int[1] { -1 };
}
else
{
int needleLength = Needle.Length;
int i = 2;
int k = 0;
JumpTable = new int[needleLength];
JumpTable[0] = -1;
JumpTable[1] = 0;
while (i <= needleLength)
{
if (i == needleLength)
{
JumpTable[needleLength - 1] = k;
}
else if (Needle[k] == Needle[i])
{
k++;
JumpTable[i] = k;
}
else if (k > 0)
{
JumpTable[i - 1] = k;
k = 0;
}
i++;
}
}
}
public int[] MatchAll()
{
List<int> matches = new List<int>();
int offset = 0;
int needleLength = Needle.Length;
int m = Match(offset);
while (m != NORESULT)
{
matches.Add(m);
offset = m + needleLength;
m = Match(offset);
}
return matches.ToArray();
}
public int Match()
{
return Match(0);
}
public int Match(int offset)
{
ComputeJumpTable();
int haystackLength = Haystack.Length;
int needleLength = Needle.Length;
if ((offset >= haystackLength) || (needleLength > ( haystackLength - offset)))
return NORESULT;
int haystackIndex = offset;
int needleIndex = 0;
while (haystackIndex < haystackLength)
{
if (needleIndex >= needleLength)
return haystackIndex;
if (haystackIndex + needleIndex >= haystackLength)
return NORESULT;
if (Haystack[haystackIndex + needleIndex] == Needle[needleIndex])
{
needleIndex++;
}
else
{
//Naive solution
haystackIndex += needleIndex;
//Go back
if (needleIndex > 1)
{
//Index of the last matching character is needleIndex - 1!
haystackIndex -= JumpTable[needleIndex - 1];
needleIndex = JumpTable[needleIndex - 1];
}
else
haystackIndex -= JumpTable[needleIndex];
}
}
return NORESULT;
}
public string Needle
{
get { return _needle; }
set { _needle = value; }
}
public string Haystack
{
get { return _haystack; }
set { _haystack = value; }
}
public int[] JumpTable
{
get { return _jumpTable; }
set { _jumpTable = value; }
}
}
}
Usage :-
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace KMPSearch
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: " + Environment.GetCommandLineArgs()[0] + " haystack needle");
}
else
{
KMPSearch search = new KMPSearch(args[0], args[1]);
int[] matches = search.MatchAll();
foreach (int i in matches)
Console.WriteLine("Match found at position " + i+1);
}
}
}
}
Try this, It'll return an array for text. ex: { "a line of" text "notepad" }:
string textToSearch = "\"a line of\" text \" notepad\"";
MatchCollection allPhrases = Regex.Matches(textToSearch, "(?<=\").*?(?=\")");
var RegArray = allPhrases.Cast<Match>().ToArray();
output: {"a line of","text"," notepad" }

Categories

Resources