I have a string value 1233873600 in C# and I have to convert it to 123-387-7300 in C#
Is there any in-built function which will do that in c#?
Cast your string to a long and use the format "{0:### ### ####}";
string.Format("{0:(###) ###-####}", 1112223333);
string phone = "1233873600".Insert(6, "-").Insert(3, "-");
You can use a simple helper method that will take the string, sterilize the input in order to remove spaces or unwanted special characters being used as a separator, and then use the ToString method built-in. If you check for various lengths you can also assure the format comes out as you see fit. For example:
public string FormatPhoneNumber(string phoneNumber)
{
string originalValue = phoneNumber;
phoneNumber= new System.Text.RegularExpressions.Regex(#"\D")
.Replace(phoneNumber, string.Empty);
value = value.TrimStart('1');
if (phoneNumber.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (phoneNumber.Length == 9)
return Convert.ToInt64(originalValue).ToString("###-###-####");
if (phoneNumber.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (phoneNumber.Length > 10)
return Convert.ToInt64(phoneNumber)
.ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));
return phoneNumber;
}
I think regex is the best option.
this site is great for finding pre made regex strings.
http://www.regexlib.com/
You might want to use regex for this. The regex for North America phone number looks like this
^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$
I guess you can use Regex.Replace method in C#.
String Format didn't work for me, so I did:
string nums = String.Join("", numbers);
return nums.Insert(0, "(").Insert(4, ")").Insert(5, " ").Insert(9, "-");
Related
I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable
string tempValue = "000000000000000" + moneyValue;
moneyValue= tempValue.Substring((tempValue).Length - 15, 15);
I'm looking to a shorter way of achieving same result , is there any?
It looks like you are looking for a more succinct way to left-pad a string with zeroes.
.NET has a built-in method for that:
moneyValue = moneyValue.PadLeft(15, '0');
PadLeft works when you start with a string. If you want to combine zero padding with formatting of a number, you can use D15 format for integers
int moneyValue = 123456;
string moneyString = $"{moneyValue:D15}";
or a custom format for other numeric types
decimal moneyValue = 1234.56;
string moneyString = $"{moneyValue:000000000000000}";
How to get text before a symbol in string ? Any ideas?
e.g. acsbkjb/123kbvh/123jh/
get text before first - "/"
Try this
string ss = myString.Split('/')[0];
You can use Substring() method to get the required part of the string.
String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');
String text2="";
if(index>=0)
text2=text.Substring(0,index);
get substring like
youstring.Substring(0,yourstring.IndexOf('/'));
The IEnumerable approach
string str = "acsbkjb/123kbvh/123jh/";
var result = new string(str.TakeWhile(a => a != '/').ToArray());
Console.WriteLine(result);
If there are no forward slashes this works without need to check the return of IndexOf
EDIT Keep this answer just as an example because the efficiency of this approach is really worse. IndexOf works faster also if you add an if statement to check the return value.
string text = "acsbkjb/123kbvh/123jh/";
string text2 = text.Substring(0, text.IndexOf("/"));
I have string like this:
strings s = "1.0E-20"
Is there a way to get only -20 from this using regex?
I tried this:
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE][-+]?[0-9]+)?
this gets me e-20 in group5 but still not just -20.
Use Regex for dealing with text, use Math(s) for dealing with numbers:
Math.Log10(Convert.ToDouble("1.0E-20")) // returns -20
To make sure your string input is a valid double use TryParse:
double d, result = 0.0;
if (Double.TryParse("1.0E-20", out d))
{
result = Math.Log10(d);
}
else
{
// handle error
}
Also, if you want to get the 1.0 (multiplier) from your input:
var d = Convert.ToDouble("1.0E-20");
var exponent = Math.Log10(d);
var multiplier = d / exponent;
No need for Regex when string methods can do wonders
string str = "1.0E-20";
str = str.Substring(str.IndexOf('E') + 1);
You can do that without Regex like:
string s = "1.0E-20";
string newStr = s.Substring(s.IndexOf('E') + 1);
Later you can parse the string to number like:
int number;
if (!int.TryParse(newStr, out number))
{
//invalid number
}
Console.WriteLine(number);
You can also use string.Split like:
string numberString = s.Split('E')[1]; //gives "-20"
Its better if you add check for string/array length when access string.Substring or accessing element 1 after split.
var x = str.IndexOf("E") != -1 ? str.Substring(str.IndexOf("E") + 1) : "1";
If you want to use regular expressions to achieve this, you should switch up your capture groups.
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE])([-+]?[0-9]+)?
Group 6 will contain -20 with your given example with the regular expression above. Note how the parentheses have moved. We might need more information from you though. Do you have any more sample data? What's the end goal here?
I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');
I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing
the input value and the format as the parameter using C#
You can use the ToString method with a standard or custom format string
For example:
string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"
You can read more about formating values here http://www.csharp-examples.net/string-format-double/
decimal value = 1.2345;
string rounded = value.ToString("d2");
private string sDecimalFormat = "0.00";
decimal d = 120M;
txtText.Text = d.ToString(sDecimalFormat);
You could then have a setting for decimal format eg:
txtText.Text = d.ToString(Settings.DecimalFormat);
String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/
I think the following might work:
String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);
fmt being the format you want to use and inpString being the string entered by the user.
Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.
There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...
I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be
But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)
You can then make a method like
Public string GetString(string Format, object value)
{
return string.Format(Format, value);
}
Something like this?