Add separator to string? - c#

I got here an sample string output in numbers:
123456789
But What my goal is to make it like this:
Format: 123-45-6789
I was able to look for some codes here but they all have a fix interval , which is not fit from what I am making. It is required to make the input format to be like this "123-45-6789" but when saving it is only required 9 characters long because there is a limit to the space where it should be stored so I used this code to met the 9 characters long storation.
Input.Text = Input.Text.Trim().Replace("-", string.Empty);
Bio.SetString(UserName, "9Character", Input.Text.Trim());
But when displaying it again , it is again required to be on this format , 123-45-6789. Which is my problem.

You can also try something like:
string val = "123456789";
val = val.Substring(0, 3) + "-" + val.Substring(3, 2) + "-" + val.Substring(5) ;
Here is a working DEMO

something like,
string number = "123456789";
var output = Regex.Replace(number,
#"^(\d{3})[ -]?(\d{2})[ -]?(\d{4})( x\d+)?",
#"$1-$2-$3$4", RegexOptions.IgnorePatternWhitespace);
Console.WriteLine($"formated {output}");
output : formated 123-45-6789
Demo

Related

Can I shorten this code with a loop in C#?

I have this code written in C# but looks kind of "bad" and I would like to shorten it somehow and keep it clean and simple.
All this code works pretty fine but I want to know if there's any other way I can achieve the same thing.
EDIT: I forgot to mention that the firstLine has a bad date format attached with it, so it is like this: "This_is_my_first_line_20220126". So I split the string and then only join it with the corrected date. The problem is that I can never know how long the new string would be and I don't want to handle the code like this and go up to 100 parts.
Here's my code:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
string firstLine = lines.FirstOrDefault();
//note: firstLine looks like this: This_is_my_first_line_20220126
string[] sub = firstLine.Split('_');
string name="";
if(sub.Length==2)
name = sub[0]+"_"+sub[1]+"_"+correctDate;
else if(sub.Length==3)
name = sub[0]+"_"+sub[1]+"_"+sub[2]+"_"correctDate;
...
else if(sub.Length==20)
name = sub[0]+"_"+ ... "_" + sub[19];
Now, my final name value should be "This_is_my_line_26012022" but I want it to depend on the length of the given string. So far I know that the maximum length would go up to 20 but I don't want my code to look like this. Can I shorten it somehow?
you can find the LastIndexOf the underscore and drop the date by using Substring:
string firstLine = "This_is_my_first_line_20220126";
string correctDate = "26012022";
string correctString = firstLine.Substring(0, firstLine.LastIndexOf("_") + 1) + correctDate;
Still a little perplexed with the split aproach, but this a way to join back all elements
string name = string.Join("_", sub.Take(sub.Length - 1).Append(correctDate));
Or use the substring method (and no need of all that split & join)
name = firstLine.Substring(0, firstLine.LastIndexOf("_") +1) + correctDate;
I forgot to mention that firstLine has a bad date format like "This_is_my_Line_20220125"
If you want to correct just the first line:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
lines[0] = lines[0][..^8] + correctDate;
[..^8] uses C# 9's "indices and ranges" feature, that allows for a more compact way of taking a substring. It means "from the start of the string, up to the index 8 back from the end of the string".
If you get a wiggly line and possibly a messages like "... is not available in C# version X" you can use the older syntax, which would be more like lines[0] = lines[0].Remove(lines[0].Length - 8) + correctDate;
If you want to correct all lines:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
for(int x = 0; x < lines.Length; x++)
lines[x] = lines[x][..^8] + correctDate;
If the incorrect date isn't always 8 characters long, you can use LastIndexOf('_') to locate the last _, and snip it to that point

How can I add a SPACE halfway through a string value?

I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;

String.Format in C#

I have an values like
1,000
25,000
500,000
Need to convert above values as like below without comma
1000
25000
500000
How to acheive this in C#?
how to get reverse output of this -
string.Format("{0:n}", 999999)
You can use the Replace function of the string class like so:
string str = "25,000";
str = str.Replace(",", "");
EDIT:
As suggested by Matthew Watson from the comments
If the string is returned from string.Format("{0:n}", 999999) run on a
machine in a locale that uses "." as the thousands separator, this
will fail
updated answer:
string num = "25,000";
NumberFormatInfo currentInfo = CultureInfo.CurrentCulture.NumberFormat;
num = num.Replace(currentInfo.NumberGroupSeparator, "");

Numeric fields lose leading zero while writing CSV in c#

I'm using an ASP.NET application which exports my clients data to CSV, I need my clients Phone number to be with the leading Zero.
I need the phone numbers to be without "-" and without quotations, and due to the nature of my application I cannot use 3rd party products such as EPPLUS.
I've tried to put a space and let the CSV "understand" that I need the phone number as text , but that doesn't seem right.
I would like to know how to make the excel include the leading zero , without using 3rd party products.
Thanks
Change the data that is saved in the csv with the following format:
="00023423"
CSV example:
David,Sooo,="00023423",World
This will show 00023423 in excel and not 23423.
public void CreatingCsvFiles(Client client)
{
string filePath = "Your path of the location" + "filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimiter = ",";
string[][] output = new string[][]{
new string[]{ "=\"" + client.phone + "\"", client.name }
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}
Inspired from http://softwaretipz.com/c-sharp-code-to-create-a-csv-file-and-write-data-into-it/
The important part :
"=\"" + client.phone + "\"", client.name
If the phone number is an int, of course you add .toString().
Print phone number to CSV with prepended ' (single quote), so it looks like:
"Some Name","'0000121212"
Excel should treat this 0000121212 as string then.
I believe converting the number into a formula like the accepted answer might not be a helpful solution for all.
The alternate solution I went with is to just add a tab space before the integer value.
Example:
Taking phoneNumber as a string variable which contains our int value
Solution:
"\t" + phoneNumber
If you know already how much numbers has to be inside phone you can do like this
phoneNumber.ToString("000000000000")
In this example I consider that phoneNumber is an int and required length of numbers is 12.

C# , Substring How to access last elements of an array/string using substring

I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on.
The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary.
My code statement is something like this
for( int 1= 0;i< filestoextract.count;1++)
{
// The filestoextract contains 35 strings
string extractname = filestoextract(i).ToString();
statSummary.writeline( extractname.substring(0,5) + "" +
extractname.substring(5,4) + "" + extractname.substring(9,2) + "" +
extractname.substring(11,2));
}
When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that.
For the last 8 digits, it's just:
extractname.Substring(extractname.Length-8)
oh, I'm sorry, and so for your code could be:
int l = extractname.Length;
statSummary.WriteLine(extractname.substring(0,l-8) + "" +
extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" +
extractname.Substring(l-2,2));
As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g.
UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly.
var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source
foreach (var file in filestoextract)
{
var dateStr = file.Substring(file.Length-dateFormat.Length);
if (ValidateDate(dateStr, dateFormat))
{
var id = file.Substring(0, file.Length - (dateFormat.Length+1));
// do something with data
}
else
{
// handle invalid filename
}
}
public bool ValidateDate(stirng date, string date_format)
{
try
{
DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
You could use a Regex :
match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" );
Console.WriteLine (match.Groups["code"] );
Console.WriteLine (match.Groups["date"] );
To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily.
The date group takes the last six characters of the string. . says take any character and {6} says do that six times.
The code group takes all the remaining characters. * says take as many characters as possible.
for each(string part in stringList)
{
int length = part.Length;
int start = length - 8;
string dateString = part.Substring(start, 8);
}
That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc)
If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this:
for( int 1= 0;i< filestoextract.count;1++)
{
string extractname = filestoextract[i].ToString();
string ID = extractname.substring(0, extractname.IndexOf(','));
string Date = extractname.substring(extractname.IndexOf(','));
Console.WriteLine(ID + Date);
}

Categories

Resources