formatting string in MVC /C# - c#

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?
Thanks.

By using regex:
public static string FormatTest1(string num)
{
string formatPattern = #"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
}
// test
string test = FormatTest1("731478718861993983");
// test result: 73-1478-7188-6199-3983

If you're dealing with a long number, you can use a NumberFormatInfo to format it:
First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Next, you can use it on your numbers:
long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
After all, .Net has very good globalization support - you're better served using it!

string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));

LINQ-only one-liner:
var str = "731478718861993983";
var result =
new string(
str.ToCharArray().
Reverse(). // So that it will go over string right-to-left
Select((c, i) => new { #char = c, group = i / 4}). // Keep group number
Reverse(). // Restore original order
GroupBy(t => t.group). // Now do the actual grouping
Aggregate("", (s, grouping) => "-" + new string(
grouping.
Select(gr => gr.#char).
ToArray())).
ToArray()).
Trim('-');
This can handle strings of arbitrary lenghs.

Simple (and naive) extension method :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("731478718861993983".InsertChar("-", 4));
}
}
static class Ext
{
public static string InsertChar(this string str, string c, int i)
{
for (int j = str.Length - i; j >= 0; j -= i)
{
str = str.Insert(j, c);
}
return str;
}
}

If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:
string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);
Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be #"\B\d{4}".

string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");

My first thought is:
String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");
(don't remember if index is zero-based, in which case you should use my values -1)
but there is probably some easier way to do this...

If the position of "-" is always the same then you can try
string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-");

Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.
string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
Edit: amended code, since you said they were held as a string in your your original question

Related

How can i parse/get only the number inside the string/s?

The variable PostedId contain for example 7 strings.
For example in index 0 i see: {"id":"1234567890"}
I want in the loop FOR
To parse/extract from the current index string only the number.
So in the line :
objFacebookClient.Delete(PostedId[i]).ToString();
Instead PostedId[i] will be {"id":"1234567890"} it should be only: 1234567890 only the number.
private void button7_Click(object sender, EventArgs e)
{
var responsePost = "";
try
{
var objFacebookClient = new FacebookClient(AccessPageToken);
for (int i = 0; i < PostedId.Count; i++)
{
objFacebookClient.Delete(PostedId[i]).ToString();
}
}
catch (Exception ex)
{
responsePost = "Facebook Posting Error Message: " + ex.Message;
}
}
If I understand your question correctly, you want to get numbers in your string then parsing them to int.
If it is, you can use Char.IsDigit method to get numbers inside a string and use Int32.TryParse method to parsing it.
For example;
string s = "{\"id\":\"1234567890\"}";
char[] array = s.Where(c => Char.IsDigit(c)).ToArray();
string s1 = new string(array);
int i;
if (Int32.TryParse(s1, NumberStyles.Integer, CultureInfo.InvariantCulture, out i))
{
Console.WriteLine(i);
}
Output will be;
1234567890
Here a demonstration.
Based on your comment under Soner Gönül`s answer, you probably want to do something like this.
This is a modification of that answer; just outputting the resulting string, without parsing it to an int, which obviously will not work when including "_".
Please make sure you include details like this in your original post in future questions.
string input = "{\"id\":\"12345_67890\"}";
char[] array = input.Where(c => Char.IsDigit(c) || c == '_').ToArray();
// Will contain: "12345_67890"
string result = new string(array);
Should be easy enough to do with a string.split or making use of a regex to extract the number part of the id. I can give an example if needed
The format you have here is looks like Json.
You can use
JSON.NET to parse your string.
Make class called for example 'FaceBookResponse':
public class FaceBookResponse{
public int id { get; set; }
}
Then use JavaScriptSerializer (Reference System.Web.Extensions):
JavaScriptSerializer serializer = new JavaScriptSerializer();
In the for loop use this:
var obj = serializer.Deserialize<FaceBookResponse>();
objFacebookClient.Delete(obj.id).ToString();
you can use regx for this,
5 is minimum digits you want,
numberonly is output, strText is input text
Regex _Regex = new Regex("\\d{5,}", RegexOptions.IgnoreCase);
MatchCollection matchList = _Regex.Matches(strText);
string NumberOnly = string.Empty;
if (matchList.Count == 0)
NumberOnly = matchList(0).ToString();
//if strText = "Test12345Test6789"
//Output will be
//matchList(0) = 12345
//matchList(1) = 6789

Remove trailing pipes - '|' in c#

I have a string that looks something like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
I am trying to remove any separating '|' characters after the 30th '|' in the string so that the output string looks like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
I am trying to do it using as little code as possible, but not having much luck. Any help or ideas would be great.
You can use the TrimEnd method
string text = "stuff||||N||||||||||";
string result = text.TrimEnd('|'); //Result is stuff||||N
Brute force but only a little bit of code:
string s2 = string.Join("|", s1.Split('|').Take(31));
If you need any other processing of this kind of data (it looks like a kind of nested CSV) then string.Split() is useful to know.
string str = "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
int c = 0;
int after = 30;
StringBuilder newStr = new StringBuilder();
for(int i = 0;i < str.length; i++){
if(str[i] == '|'){
if(after != c){
newStr.append(str[i]);
c++;
}
}else{
newStr.append(str[i]);
}
}
results in
newStr == "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
A regex should do the trick:
var regex = new Regex(#"^([^\|]*\|){0,30}[^\|]*");
var match = regex.Match(input);
if(match.Success)
{
var val = match.Value;
}
If what you really want is that everything after the 30th chunk loses its '|', then try:
var chunks = input.Split('|');
var output = String.Join('|',chunks.Take(30)) + String.Concat(chunks.Skip(30));
That said, I think it sounds like what you're really looking for is probably something like:
var output = input.TrimEnd('|');
// Get the indexes of all the | characters.
int[] pipeIndexes = Enumerable.Range(0, s.Length).Where(i => s[i] == '|').ToArray();
// If there are more than thirty pipes:
if (pipeIndexes.Length > 30)
{
// The former part of the string remains intact.
string formerPart = s.Substring(0, pipeIndexes[30]);
// The latter part needs to have all | characters removed.
string latterPart = s.Substring(pipeIndexes[30]).Replace("|", "");
s = formerPart + latterPart;
}

All elements before last comma in a string in c#

How can i get all elements before comma(,) in a string in c#?
For e.g.
if my string is say
string s = "a,b,c,d";
then I want all the element before d i.e. before the last comma.So my new string shout look like
string new_string = "a,b,c";
I have tried split but with that i can only one particular element at a time.
string new_string = s.Remove(s.LastIndexOf(','));
If you want everything before the last occurrence, use:
int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
// Handle case with no commas
}
else
{
string beforeLastIndex = input.Substring(0, lastIndex);
...
}
Use the follwoing regex: "(.*),"
Regex rgx = new Regex("(.*),");
string s = "a,b,c,d";
Console.WriteLine(rgx.Match(s).Groups[1].Value);
You can also try:
string s = "a,b,c,d";
string[] strArr = s.Split(',');
Array.Resize(strArr, Math.Max(strArr.Length - 1, 1))
string truncatedS = string.join(",", strArr);

How do I remove all non alphanumeric characters from a string except dash?

How do I remove all non alphanumeric characters from a string except dash and space characters?
Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
You can try:
string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");
Where s is your string.
Using System.Linq
string withOutSpecialCharacters = new string(stringWithSpecialCharacters.Where(c =>char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-').ToArray());
The regex is [^\w\s\-]*:
\s is better to use instead of space (), because there might be a tab in the text.
Based on the answer for this question, I created a static class and added these. Thought it might be useful for some people.
public static class RegexConvert
{
public static string ToAlphaNumericOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z0-9]");
return rgx.Replace(input, "");
}
public static string ToAlphaOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z]");
return rgx.Replace(input, "");
}
public static string ToNumericOnly(this string input)
{
Regex rgx = new Regex("[^0-9]");
return rgx.Replace(input, "");
}
}
Then the methods can be used as:
string example = "asdf1234!##$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();
Want something quick?
public static class StringExtensions
{
public static string ToAlphaNumeric(this string self,
params char[] allowedCharacters)
{
return new string(Array.FindAll(self.ToCharArray(),
c => char.IsLetterOrDigit(c) ||
allowedCharacters.Contains(c)));
}
}
This will allow you to specify which characters you want to allow as well.
Here is a non-regex heap allocation friendly fast solution which was what I was looking for.
Unsafe edition.
public static unsafe void ToAlphaNumeric(ref string input)
{
fixed (char* p = input)
{
int offset = 0;
for (int i = 0; i < input.Length; i++)
{
if (char.IsLetterOrDigit(p[i]))
{
p[offset] = input[i];
offset++;
}
}
((int*)p)[-1] = offset; // Changes the length of the string
p[offset] = '\0';
}
}
And for those who don't want to use unsafe or don't trust the string length hack.
public static string ToAlphaNumeric(string input)
{
int j = 0;
char[] newCharArr = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
if (char.IsLetterOrDigit(input[i]))
{
newCharArr[j] = input[i];
j++;
}
}
Array.Resize(ref newCharArr, j);
return new string(newCharArr);
}
I´ve made a different solution, by eliminating the Control characters, which was my original problem.
It is better than putting in a list all the "special but good" chars
char[] arr = str.Where(c => !char.IsControl(c)).ToArray();
str = new string(arr);
it´s simpler, so I think it´s better !
Here's an extension method using #ata answer as inspiration.
"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"
or if you require additional characters other than hyphen...
"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"
public static class StringExtensions
{
public static string MakeAlphaNumeric(this string input, params char[] exceptions)
{
var charArray = input.ToCharArray();
var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
return new string(alphaNumeric);
}
}
If you are working in JS, here is a very terse version
myString = myString.replace(/[^A-Za-z0-9 -]/g, "");
I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.
private string MakeUrlString(string input)
{
var array = input.ToCharArray();
array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');
var newString = new string(array).Replace(" ", "-").ToLower();
return newString;
}
There is a much easier way with Regex.
private string FixString(string str)
{
return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}

String replace for personalize code generator

I must do a automatic codes generator with user-configurable string with predefined keys and can not find a good way to do it.
For example, a string
OT-{CustomCode}-{Date}-{##}
could generate codes
OT-C0001-20100420-01
OT-C0001-20100420-02
I thought of using RegExpr.Replace(), but I would have problems if the code of a customer was {##}
Any help is welcome! (and sorry for my english)
You can use string.Format():
string generated = string.Format("OT-{0}-{1}-{2}", code, date, num);
The {x} are placeholders for strings to be replaced.
Do you mean an auto-generated code definition is for example:
Foo {##} , Bar {Date}
and that will produce:
Foo 01 , Bar 20100420
Foo 02 , Bar 20100420
don't you ?
I think RegExpr.Replace() is a good solution, to the ## problem you can do something like this:
private void Generate()
{
Regex doubleSharpRegEx = new Regex("{#+}");
string customString = "Foo {####}";
string[] generatedCodes = new string[3];
for (int i = 0; i < generatedCodes.Length; i++)
{
string newString = doubleSharpRegEx.Replace(customString,
match =>
{
// Calculate zero padding for format
// remove brackets
string zeroPadding = match.Value.Substring(1, match.Value.Length - 2);
// replace # with zero
zeroPadding = zeroPadding.Replace('#', '0');
return string.Format("{0:" + zeroPadding + "}", i);
});
generatedCodes[i] = newString;
}
}
And the array generatedCodes contains:
Foo 0000
Foo 0001
Foo 0002
Foo 0003
EDIT:
Lambdas expression work only for framework 3.5.
If you need a solution for 2.0, you must only replace the lambda expression part with a delegate (obviously setting i available for the delegated method e.g. class member)
EDIT 2:
You can combine the 2 answer for example in the following code:
private void Generate2()
{
Regex customCodeRegex = new Regex("{CustomCode}");
Regex dateRegex = new Regex("{Date}");
Regex doubleSharpRegex = new Regex("{#+}");
string customString = "Foo-{##}-{Date}-{CustomCode}-{####}";
string newString = customCodeRegex.Replace(customString, "{0}");
newString = dateRegex.Replace(newString, "{1}");
newString = doubleSharpRegex.Replace(newString,
match =>
{
string zeroPadding = match.Value.Substring(1, match.Value.Length - 2);
zeroPadding = zeroPadding.Replace('#', '0');
return "{2:" + zeroPadding + "}";
});
string customCode = "C001";
string date = DateTime.Today.ToString("yyyyMMdd");
string[] generatedCodes = new string[3];
for (int i = 0; i < generatedCodes.Length; i++)
{
generatedCodes[i] = string.Format(newString, customCode, date, i);
}
}
The StringBuilder class provides an efficient replace:
string code = "C0001";
DateTime date = DateTime.Now;
int count = 1;
String formatString = "OT-{CustomCode}-{Date}-{##}";
StringBuilder sb = new StringBuilder(formatString);
sb.Replace("{CustomCode}", code);
sb.Replace("{Date}", date.ToString("yyyyMMdd"));
sb.Replace("{##}", count);
string result = sb.ToString();
But this is more useful if you're doing multiple replaces for the same tokens. Looks like you need String.Format as suggested by Elisha

Categories