How to format a fixed length string - c#

I have a fixed length string ABCDEFGHIJK, is there a way to convert this into AB-CDEFGHIJ-K using string format?

var s = "ABCDEFGHIJK";
Console.WriteLine($"{s[..2]}-{s[2..10]}-{s[^1..]}");

I have a fixed length string ABCDEFGHIJK, is there a way to convert
this into AB-CDEFGHIJ-K using string format?
Focusing on the "string format" part, we can implement IFormatProvider. This will format the string if it is EXACTLY eleven characters long, otherwise it just returns the same string back. Following the example, the "H" format stands for "hypenated":
private void button1_Click_2(object sender, EventArgs e)
{
string input = "ABCDEFGHIJK";
string output = String.Format(new MyStringFormat(), "Formatted: {0:H}", input);
Console.WriteLine(input);
Console.WriteLine(output);
}
public class MyStringFormat : IFormatProvider, ICustomFormatter
{
object IFormatProvider.GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg.GetType() != typeof(String))
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
}
}
string ufmt = format.ToUpper(CultureInfo.InvariantCulture);
if (ufmt != "H")
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
}
}
string result = arg.ToString();
if (result.Length != 11)
return result;
else
return result.Insert(2, "-").Insert(11, "-"); // see comment by Hans Passant!
}
private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
return arg.ToString();
else
return String.Empty;
}
}

howabout
var newstring = String.format("{0}-{1}-{2}", s.Substring(0,2), s.Substring(3,7), s.Substring(10,1))
you could also use interpolation and the new range stuff

var f = Regex.Replace("ABCDEFGHIJK", "^(..)(.*)(.)$", "$1-$2-$3");
...yeah, I know.
Also, dropping the {2}, etc. was inspired by Yuriy's answer here.

The Rube Goldberg way perhaps:
static void Main(string[] args)
{
string code = "ABCDEFGHIJK";
string mask = "##-########-#";
Console.WriteLine(code.Format(mask));
// AB-CDEFGHIJ-K
}
public static string Format(this string code, string mask, char token = '#')
{
StringBuilder sb = new StringBuilder(mask.Length);
int index = 0;
foreach (var item in mask)
{
if (item==token)
{
sb.Append(code[index++]);
}
else
{
sb.Append(item);
}
}
return sb.ToString();
}
Edit 1
replaced the space ' ' character placeholder with the pound sign '#' for better clarity.

Related

Reading date columns from Excel

I am trying to read date cell from Excel file:
private string GetDateValueFromRowOrNull(ISheet worksheet, int row, int column, StringBuilder exceptionMessage, CellType? cellType = null)
{
var cell = worksheet.GetRow(row).GetCell(column);
if (cell == null)
{
return string.Empty;
}
if (cellType != null)
{
cell.SetCellType(cellType.Value);
}
var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;
if (cellValue != null)
{
return cellValue;
}
return String.Empty;
}
But I am getting an error while trying to return the cellValue:
Can not implicitly convert type System.DateTime to string
if (cellValue != null)
{
return cellValue;
}
I am using NPOI for the Excel functions.
You can read the datetime value as string from excel then convert it to a DateTime object.
Sample converter code:
public static DateTime GetDateTime(string day, string month, string year)
{
try
{
return Convert.ToDateTime(string.Format("{0} {1}, {2}", (object)day, (object)month, (object)year));
}
catch (Exception ex)
{
throw ex;
}
}
If you require a DateTime to be returned from your method you need to change the method signature to return DateTime instead of string. Given the possibility of a null value, I also suggest you actually return a nullable date and make sure callers of this method handle nulls the same way you were expecting them to handle empty string:
private DateTime? GetDateValueFromRowOrNull(ISheet worksheet, int row, int column, StringBuilder exceptionMessage, CellType? cellType = null)
{
var cell = worksheet.GetRow(row).GetCell(column);
if (cell == null)
{
return null;
}
if (cellType != null)
{
cell.SetCellType(cellType.Value);
}
var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;
if (cellValue != null)
{
return cellValue;
}
return null;
}
I have sorted it. #Fredy’s comment was right.
var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;
if (cellValue != null)
{
return cellValue.ToString();
}

detect format of date and convert it to exact format "yyyy-MM-dd"

I have method to convertDatefromExcelToSQL which take date value from excel file and convert it to exact format "yyyy-MM-dd"
the problem occured when date format in the PC different from the formate i declared
I want to modify my method to detect date format and convert it to exact format "yyyy-MM-dd"
public static string convertDatefromExcelToSQL(string excelDate)
{
string sdat = "";
DateTime dat;
sdat = ((string.IsNullOrEmpty(excelDate)) ? sdat : excelDate);
if (MIB.IsDouble(sdat))
{
dat = DateTime.FromOADate(double.Parse(sdat));
}
else
{
if (sdat.Contains(":"))
{
sdat = sdat.Split(' ')[0];
}
dat = DateTime.ParseExact(sdat, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
return dat.ToString("yyyy-MM-dd");
}
public static bool IsDouble(string text)
{
Double num = 0;
bool isDouble = false;
// Check for empty string.
if (string.IsNullOrEmpty(text))
{
return false;
}
isDouble = Double.TryParse(text, out num);
return isDouble;
}
public static string CDtStr(object v)
{
string lReturnValue = string.Empty;
DateTime lOutDateTime = new DateTime();
if (v != null)
{
if (v != DBNull.Value)
{
if (DateTime.TryParse(v.ToString(), out lOutDateTime))
lReturnValue = lOutDateTime.ToString("yyyy-MM-dd");
}
}
return lReturnValue;
}

String format and Formatted string

I am trying to format a string lets say
"Hello george, how are you?"
I just want "george" in red color. Is there any way I can use String.Format and FormattedString side by side?
I tried using:
var text = new FormattedString();
text.Spans.Add(new Span {
Text = Localize.GetString("irs", String.Empty),
ForegroundColor = Colors.RedColor
});
label.FormattedText = String.Format(
Localize.GetString("instructions", String.Empty),
text
);
However this does not work. Is there any proper way to actually do this. I want localization so I don't want to split the text into multiple localization strings.
You can use an intercept provider in string.Format.
For illustrative purposes, I choose XAML format as output, and then convert it into FormattedString (but more concise formats like JSON can also be used).
First, let's implement the intercept provider - which will convert your string.Format's output into Span(s):
public class InterceptProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(String format, Object obj, IFormatProvider provider)
{
string spanText;
// Use default for all other formatting.
if (obj is IFormattable)
spanText = ((IFormattable)obj).ToString(format, System.Globalization.CultureInfo.CurrentCulture);
else
spanText = obj.ToString();
return $"</Span><Span ForegroundColor=\"Red\">{spanText}</Span><Span>";
}
}
Add an extension method to integrate the interceptor with string.Format.
public static class FormatExtensions
{
static ColorTypeConverter _typeConverter = new ColorTypeConverter();
static InterceptProvider _interceptor = new InterceptProvider();
public static string InterceptFormat(this string sourceStr, params object[] args)
{
return $"<FormattedString><Span>{string.Format(_interceptor, sourceStr, args)}</Span></FormattedString>";
}
And, finally an helper method that converts XAML to FormattedString object.
public static FormattedString ToFormattedString(this string xamlStr)
{
var toReturn = new FormattedString();
if (string.IsNullOrWhiteSpace(xamlStr))
return toReturn;
Span span = null;
using(var strReader = new StringReader(xamlStr))
{
using(var xmlReader = XmlReader.Create(strReader))
{
while (xmlReader.Read())
{
if (xmlReader.IsStartElement())
{
switch (xmlReader.Name)
{
case "Span":
span = new Span();
while (xmlReader.MoveToNextAttribute())
{
switch (xmlReader.Name)
{
case "ForegroundColor":
var color = xmlReader.Value;
if (!string.IsNullOrEmpty(color))
span.ForegroundColor = (Color)_typeConverter.ConvertFromInvariantString(color);
break;
}
}
if (xmlReader.IsStartElement() || xmlReader.MoveToContent() == XmlNodeType.Element)
{
span.Text = xmlReader.ReadString();
toReturn.Spans.Add(span ?? new Span());
}
break;
}
}
}
}
}
return toReturn;
}
USAGE:
label.FormattedText = Localize.GetString("instructions", String.Empty)
.InterceptFormat(text).ToFormattedString();
Or,
lbl.FormattedText = "{0} It is now {1:d} at {1:t}"
.InterceptFormat("Morning!", DateTime.Now)
.ToFormattedString();

Ignoring Characters in a file read c#

I am reading a file for school and I am trying to ignore accents.
I used CultureInfo but it doesn't work for me is there another way??
(example .... Clémentine = clementine)
public static void SearchName()
{
string lineIn = String.Empty;
string[] BoatInfo = new string[5];
Console.WriteLine();
FileStream fs = new FileStream(#"FrenchMF.txt", FileMode.Open, FileAccess.Read);
StreamReader inputStream = new StreamReader(fs);
lineIn = inputStream.ReadLine();
string input = String.Empty;
Console.WriteLine();
Console.Write("Enter Vessel Name :");
input = Console.ReadLine().ToLower().Trim();
string CheckInput = String.Empty;
while(lineIn != null)
{
BoatInfo = lineIn.Split(',');
CheckInput = BoatInfo[0].ToLower();
if (input.Equals(CheckInput))
{
Console.WriteLine("its a Match" );
}
else
{
Console.WriteLine("No Match Found!! ");
return;
}
}
}
You can create an extension method for string:
public static string RemoveDiacritics(this string #this) {
var normalizedString = #this.Normalize(System.Text.NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString) {
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark) {
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
And then you can say input.RemoveDiacritics().
In order for the extension method to work, you must put it in a static class:
public static class ScorableExtensions {
public static string RemoveDiacritics(this string #this) {
//the one above
}
}
string.Compare(s1, s2, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace);
See this answer
Of course, you can create your own CultureInfo - you do not have to use the CurrentCulture:
string.Compare(s1, s2, new CultureInfo("fr-FR"), CompareOptions.IgnoreNonSpace);

Checking string with custom format in c#

I'm creating a command system for my application but i don't know how to make c# recognize a pattern in my string.
Example:
add(variable1, variable2)
How to make c# recognize addUser(...) and do some stuff?
I'm currently using string contains but if user type add()()()()() or add((((((, it still work!
Please help!
sorry about my english!
This may not be perfect, but might give you some ideas :)
static void Main(string[] args)
{
string example_input = "xxxxx Add(user1, user2) xxxxxx";
string myArgs = getBetween2(example_input, "Add(", ")"); //myArgs = "user1, user2"
if (myArgs != "EMPTY")
{
myArgs = myArgs.Replace(" ", ""); // remove spaces... myArgs = "user1,user2"
string[] userArray = myArgs.Split(',');
foreach (string user in userArray)
{
Console.WriteLine(user);
//Your code here
}
}
Console.ReadKey(); //pause
}
static string getBetween2(string strSource, string strStart, string strEnd)
{
try
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "EMPTY";
}
}
catch
{
return "EMPTY";
}
}

Categories

Resources