C# padLeft, not adding pad - c#

I am writing a method to format a phone number and also add padding to the beginning if there are less than 10 digits in the initial array. I am only failing use cases where less than 10 digits are input and my method is clearly not adding the padding. The most common mistake is using the wrong padcount parameter. I am sure I am missing something simple.
public static string CreatePhoneNumber(int[] numbers)
{
string numbas = string.Join("", numbers);
string ammendNumbas = numbas;
char pad = '0';
if ( numbas.Length < 10)
{
ammendNumbas = numbas.PadLeft(10, pad);
}
string formatString = "(###) ###-####";
var returnValue = Convert.ToInt64(ammendNumbas)
.ToString(formatString.Substring(0,ammendNumbas.Length+4))
.Trim();
return returnValue;
}

When you use Convert.ToInt64 you would be removing all padding because padding can only be applied to strings. You would need to not convert the value back to an integer after applying padding.
I think what you want is this:
public static string CreatePhoneNumber(int[] numbers)
{
Int64 numbas = Convert.ToInt64(string.Join("", numbers));
return numbas.ToString("(000) 000-0000");
}

What BlueMonk said is correct but you can do the padding with String.Format
public static string CreatePhoneNumber(int[] numbers)
{
string phoneNumberStr = string.Join("", numbers);
var phoneNumber = Convert.ToInt64(phoneNumberStr);
return String.Format("{0:(###) ###-####}", phoneNumber);
}
This is not tested but should work.

When you call Convert.ToInt64, the information of leading zeroes is lost. You can use substrings of your padded string representation to extract the digit groups:
public static string CreatePhoneNumber(int[] numbers)
{
var numberString = string.Join("", numbers);
var paddedNumbers = numberString.PadLeft(10, '0');
return $"({paddedNumbers.Substring(0, 3)}) {paddedNumbers.Substring(3, 3)}-{paddedNumbers.Substring(6)}";
}

Related

Extracting double value from a string c#

I want to extract the double from my string.
buff = "VA VV_CELL1 3.55"
When i use the following code
private void GetLine(string msg, string buff, double numb)
{
comPort.WriteLine(msg);
Thread.Sleep(50);
buff = comPort.ReadExisting();
Thread.Sleep(50);
MatchCollection matches = Regex.Matches(buff, #".*?([-]{0,1} *\d+.\d+)");
List<double> doubles = new List<double>();
foreach (Match match in matches)
{
string value = match.Groups[1].Value;
value = value.Replace(" ", "");
doubles.Add(double.Parse(value));
Thread.Sleep(200);
numb = doubles[0];
}
}
This code work for my other strings but "CELL1" contains a number so i dont get the wanted value "3.55" any ideas?
Why you don't simply split this string and take the last part?
string numberPart = buff.Split().Last();
double num;
bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);
Another way is to use Substring and LastIndexOf(which fails if there is no space):
string numberPart = buff.Substring(buff.LastIndexOf(' ')).Trim();
To help on your comment:
I'd use a method that returns a double?(double that can be null):
double? GetNumber(string buff)
{
string numberPart = buff.Split().Last();
double num;
bool validNum = double.TryParse(numberPart, NumberStyles.Any, CultureInfo.InvariantCulture, out num);
if (validNum)
return num;
else
return null;
}
Now you can use the method and you even know whether the number could be parsed successfully or not:
double? result = GetNumber("VA VV_CELL1");
bool wasValid = result.HasValue;
if(wasValid)
{
double value = result.Value;
}
Try, this regex expression : \s+\d+(.)?\d+
I assume you want to capture both doubles and integers, otherwise you could write \d+\.\d+. This :
Regex.Matches("VA VV_CELL1 3.55",#"\d+\.\d+")[0]
Returns 3.55 but can't capture 355.
You can capture an integer or decimal preceded by whitespace with \s+\d+(\.\d+)?.
Regex.Matches("VA VV_CELL1 3.55",#"\s+\d+(\.\d+)?")[0]
Returns 3.55 while
Regex.Matches("VA VV_CELL1 355",#"\s+\d+(\.\d+)?")[0]
Returns 355
If you want to capture only the last field you can use \s+\d+(\.\d+)?$,eg:
Regex.Matches("VA VV_CELL1 3.54 3.55",#"\s+\d+(\.\d+)?$")[0]
Returns 3.55
You don't need to trim whitespace because double.Parse ignores it. You can change the pattern to capture the number in a separate group though, by surrounding the digits with parentheses :
Regex.Matches("VA VV_CELL1 3.54 3.55",#"\s+(\d+(\.\d+)?)$")[0].Groups[1]
You need to use Groups[1] because the first group always returns the entire capture

Replace a substring

I have an input string. I need to replace its prefix (until first dot) with an other string.
The method signature:
string MyPrefixReplace(string input, string replacer)
Examples:
string res = MyPrefixReplace("12.345.6789", "000")
res = "000.345.6789";
res = MyPrefixReplace("908.345.6789", "1")
res = "1.345.6789";
Is there a way not to extract a sub-string before first dot and make a Replace**?
I.e - I don't want this solution
int i = input.IndexOf(".");
string rep = input.Substring(0,i);
input.Replace(rep,replacer);
Thanks
You could use String.Split
public string MyPrefixReplace(string source, string value, char delimiter = '.')
{
var parts = source.Split(delimiter);
parts[0] = value;
return String.Join(delimiter.ToString(), parts);
}
Live demo
Using String.IndexOf and String.Substring ist the most efficient way. In your approach you have used the wrong overload of Substring. String.Replace is pointless anyway since you don't want to replace all occurences of the first part but only the first part.
Therefore you don't have to take but to skip the the first part and prefix another. This works as desired:
public static string MyPrefixReplace(string input, string replacer, char prefixChar = '.')
{
int index = input.IndexOf(prefixChar);
if (index == -1)
return input;
return replacer + input.Substring(index);
}
Your input:
string result = MyPrefixReplace("908.345.6789", "1"); // 1.345.6789
result = MyPrefixReplace("12.345.6789", "000"); // 000.345.6789
Personally, I'd split the string up to get around this problem, although there's obviously other ways of doing this, this would be my approach:
string Input = "123.456.789"
string[] SplitInput = Input.Split('.');
SplitInput[0] = "321";
string Output = String.Join('.', SplitInput);
Output should be "321.456.789".

Is there an easy way to trim the last three characters off a string

I have strings like this:
var a = "abcdefg";
var b = "xxxxxxxx";
The strings are always longer than five characters.
Now I need to trim off the last 3 characters. Is there some simple way that I can do this with C#?
In the trivial case you can just use
result = s.Substring(0, s.Length-3);
to remove the last three characters from the string.
Or as Jason suggested Remove is an alternative:
result = s.Remove(s.Length-3)
Unfortunately for unicode strings there can be a few problems:
A unicode codepoint can consist of multiple chars since the encoding of string is UTF-16 (See Surrogate pairs). This happens only for characters outside the basic plane, i.e. which have a code-point >2^16. This is relevant if you want to support Chinese.
A glyph (graphical symbol) can consist of multiple codepoints. For example ä can be written as a followed by a combining ¨.
Behavior with right-to-left writing might not be what you want either
You want String.Remove(Int32)
Deletes all the characters from this string beginning at a specified
position and continuing through the last position.
If you want to perform validation, along the lines of druttka's answer, I would suggest creating an extension method
public static class MyStringExtensions
{
public static string SafeRemove(this string s, int numCharactersToRemove)
{
if (numCharactersToRemove > s.Length)
{
throw new ArgumentException("numCharactersToRemove");
}
// other validation here
return s.Remove(s.Length - numCharactersToRemove);
}
}
var s = "123456";
var r = s.SafeRemove(3); //r = "123"
var t = s.SafeRemove(7); //throws ArgumentException
string a = "abcdefg";
a = a.Remove(a.Length - 3);
string newString = oldString.Substring(0, oldString.Length - 4);
If you really only need to trim off the last 3 characters, you can do this
string a = "abcdefg";
if (a.Length > 3)
{
a = a.Substring(0, a.Length-3);
}
else
{
a = String.Empty;
}

How can I parse the int from a String in C#?

I have a string that contains an int. How can I parse the int in C#?
Suppose I have the following strings, which contains an integer:
15 person
person 15
person15
15person
How can I track them, or return null if no integer is found in the string?
You can remove all non-digits, and parse the string if there is anything left:
str = Regex.Replace(str, "\D+", String.Empty);
if (str.Length > 0) {
int value = Int32.Parse(str);
// here you can use the value
}
Paste this code into a test:
public int? ParseAnInt(string s)
{
var match = System.Text.RegularExpressions.Regex.Match(s, #"\d+");
if (match.Success)
{
int result;
//still use TryParse to handle integer overflow
if (int.TryParse(match.Value, out result))
return result;
}
return null;
}
[TestMethod]
public void TestThis()
{
Assert.AreEqual(15, ParseAnInt("15 person"));
Assert.AreEqual(15, ParseAnInt("person 15"));
Assert.AreEqual(15, ParseAnInt("person15"));
Assert.AreEqual(15, ParseAnInt("15person"));
Assert.IsNull(ParseAnInt("nonumber"));
}
The method returns null is no number is found - it also handles the case where the number causes an integer overflow.
To reduce the chance of an overflow you could instead use long.TryParse
Equally if you anticipate multiple groups of digits, and you want to parse each group as a discreet number you could use Regex.Matches - which will return an enumerable of all the matches in the input string.
Use something like this :
Regex r = new Regex("\d+");
Match m = r.Match(yourinputstring);
if(m.Success)
{
Dosomethingwiththevalue(m.Value);
}
Since everyone uses Regex to extract the numbers, here's a Linq way to do it:
string input = "15person";
string numerics = new string(input.Where(Char.IsDigit).ToArray());
int result = int.Parse(numerics);
Just for the sake of completeness, it's probably not overly elegant. Regarding Jaymz' comment, this would return 151314 when 15per13so14n is passed.

How can I parse an integer and the remaining string from my string?

I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"

Categories