I found that with long.Parse, ToString can take argument and I can format it to desired string, for example.
Input:
Console.WriteLine(long.Parse("123").ToString("#-#-#"));
Output:
1-2-3
I wanted to do something similar with string, lets say I wanna parse string to format ####-###-####. Is there any way to do it without regex with one liner like example above?
EDIT
Ok, so I may be misunderstood, I didn't want to parse numbers, but string instead. I can do in python like:
'{}-{}-{}'.format(*'abc') and I will receive a-b-c. In C# it seems to work only with numbers.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.WriteLine("helloWorld".ToPhoneNumber("###-###-####"));
}
}
public static class AdvancedFormatString
{
public static string ToPhoneNumber(this string strArg, string outputformat)
{
if (outputformat == null)
return strArg;
var sb = new StringBuilder();
var i = 0;
foreach (var c in outputformat)
{
if (c == '#')
{
if (i < strArg.Length)
{
sb.Append(strArg[i]);
}
i++;
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
}
}
Related
I want to put a data from simple csv file into the records containing custom made class.
Here is my code:
using System;
using CsvHelper;
using System.IO; // for accessing the files
using System.Globalization;
using System.Linq; // to call a list enumerable
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
namespace Reading_CSV_Files
{
class Program
{
static void Main(string[] args)
{
ReadCSVFile(#"C:\path_to_my_file\file.csv");
}
public static void ReadCSVFile(String filePath)
{
if (filePath == null)
{
return;
}
using (var streamReader = new StreamReader(filePath) )
{
using (var foodFileCSVReader = new CsvReader(streamReader,
CultureInfo.InvariantCulture))
{
//var records = foodFileCSVReader.GetRecords<dynamic>().ToList();
var records = foodFileCSVReader.GetRecords<Pizza>().ToList();
// replace dynamic type argument on our records
}
}
}
}
public class Pizza
{
// attributes
[Name("Name")]
public String Name { get; set; }
[Name("PLN_Cost")]
public double Price { get; set; }
}
}
The csv file looks like this:
Screenshot from csv file
The file was saved as comma separated. I found some advices with manual setting it up, but currently it says, this field is read-only.
CsvHelper.HeaderValidationException: Header with name 'Name'[0] was not found.
Header with name 'PLN_Cost'[0] was not found.
If the program is going to be using CSV files which might have a comma or semi-colon as the separator, you could read the first line and set the separator to either of those, like this:
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
public class Pizza
{
// attributes
[Name("Name")]
public String Name { get; set; }
[Name("PLN_Cost")]
public decimal Price { get; set; }
public override string ToString()
{
return $"{Name} - {Price}";
}
}
public static List<Pizza> ReadCSVFile(String filePath)
{
if (!File.Exists(filePath))
{
return new List<Pizza>();
}
var sep = ";";
/* Check the header for the separator character to use. */
string headerLine = File.ReadLines(filePath).First();
if (headerLine?.IndexOf(',') >= 0) { sep = ","; }
using (var sr = new StreamReader(filePath))
{
var config = new CsvConfiguration(CultureInfo.CurrentCulture)
{
Delimiter = sep,
Encoding = Encoding.UTF8
};
using (var foodFileCSVReader = new CsvReader(sr, config))
{
return foodFileCSVReader.GetRecords<Pizza>().ToList();
}
}
}
static void Main(string[] args)
{
var pp = ReadCSVFile(#"C:\temp\PizzaPrices.csv");
Console.WriteLine(string.Join("\r\n", pp));
Console.ReadLine();
}
}
}
Note that it is better to use the decimal type for money instead of the double type.
You might need additional code to set the decimal separator to be used.
I want to to extract multiple numbers from a string. The string may be like below:
hello:123.11,good:456,bye:789.78
And I want to get 3 numbers(including both integer and float numbers): 123.11, 456, 789.78 by C#.
Updated: including float number, not all integer.
How?
Thanks!
Try using Matches method of the Regex class with regex to get all the occurrence of the digits.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var subjectString = "hello:123,good:456,bye:789";
var result = Regex.Matches(subjectString, #"[-+]?(\d*[.])?\d+");
foreach(var item in result)
{
Console.WriteLine(item);
}
}
}
DOT NET FIDDLE
using System.IO;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string digitsOnly = String.Empty;
string s = "2323jh213j21h3j2k19hk";
List<int> MyNumbers = new List<int>();
foreach (char c in s)
{
if (c >= '0' && c <= '9') digitsOnly += c;
else
{
int NumberToSave;
bool IsIntValue = Int32.TryParse(digitsOnly, out NumberToSave);
if (IsIntValue)
{
MyNumbers.Add(Convert.ToInt16(digitsOnly));
}
digitsOnly=String.Empty;
}
}
foreach (int element in MyNumbers)
{
Console.WriteLine(element);
}
}
}
My aim is to "Sanitize a string".
The class should do:
trim an input
make the first letter upper case.
Could you please tell me:
Is there a way to better code it?
Would it make sense to use a PARAMETER for a method like: CapitalizeFirstLetterTrim(string x)
when I initiate an object I need write a lot of code like below, any other way to make it shorter?
UserInputSanitizer myInput = new UserInputSanitizer();
myInput.Input = " ciao world";
string ouput = myInput.CapitalizeFirstLetterTrim();
Useful resource http://msdn.microsoft.com/en-us/library/bb311042.aspx
----------- CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebProject.Core.Utilities
{
public class UserInputSanitizer
{
// Backing variables
private string _input;
// Properties
public string Input
{
set { _input = value; }
}
private string _output;
// Backing variables
// Properties
public string Output
{
get { return _output; }
}
public string CapitalizeFirstLetterTrim()
{
// Trim
_input.Trim();
// Make First letter UpperCase and the rest levae lower case
_output = _input.Substring(0, 1).ToUpper() + _input.Substring(1);
return Output;
}
}
}
I think I would create an extension method on string instead:
public static class MyStringExtensions{
public static string Sanitize(this string input)
{
if(input == null) throw new ArgumentNullException("input");
var trimmed = input.Trim();
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(trimmed);
}
}
You would call the method like this:
var s = " Unsanitized ";
var sanitized = s.Sanitize();
You can use Extension Method to support your requirement
With extension methods , you can use method as if they are part of System.String class.
See Here
I would use an extension method for the string class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebProject.Core.Utilities
{
public static class StringExtensions
{
public static string Sanitize(this string s)
{
//your code to sanitize your string, for example
if(s == null) throw new ArgumentNullException("s");
var trimmed = input.Trim();
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(trimmed);
}
}
}
Then you can use:
string s = " UnsanitizedString";
s = s.Sanitize();
I would make the class and methods static
namespace WebProject.Core.Utilities
{
public static class UserInputSanitizer
{
public static string CapitalizeFirstLetterTrim(string input)
{
// Trim
input.Trim();
// Make First letter UpperCase and the rest levae lower case
return input.Substring(0, 1).ToUpper() + input.Substring(1);
}
}
}
and then you would call it like this:
string ouput = UserInputSanitizer.CapitalizeFirstLetterTrim(" ciao world");
Rather than a utility class, it may make more intuitive sense to write this as an extension method for string so you can just call it directly from the literal. Much less overhead.
The following code outputs:
http://www.google.com
http://www.google.com&lang
What is the simplest way to change the code so it outputs:
http://www.google.com
http://www.google.com&lang=en¶m2=this¶m3=that
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestRegex9928228
{
class Program
{
static void Main(string[] args)
{
string text1 = "try out [url=http://www.google.com]this site (http://www.google.com)[/url]";
Console.WriteLine(text1.ExtractParameterFromBbcodeUrlElement());
string text2 = "try out [url=http://www.google.com&lang=en¶m1=this¶m2=that]this site (http://www.google.com)[/url]";
Console.WriteLine(text2.ExtractParameterFromBbcodeUrlElement());
Console.ReadLine();
}
}
public static class StringHelpers
{
public static string ExtractParameterFromBbcodeUrlElement(this string line)
{
if (line == null)
return "";
else
{
if (line.Contains("]"))
{
List<string> parts = line.BreakIntoParts(']');
if (parts[0].Contains("="))
{
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return sides[1];
else
return "";
}
else
return "";
}
else
return "";
}
}
public static List<string> BreakIntoParts(this string line, char separator)
{
if (String.IsNullOrEmpty(line))
return new List<string>();
else
return line.Split(separator).Select(p => p.Trim()).ToList();
}
}
}
Simplest or most efficient? You're asking two different questions it seems. Simplest would be something like this:
Change:
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return sides[1];
To:
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return parts[0].Replace(sides[0], "");
Edit: Looks like you changed title to remove "most efficient". Here's the simplest change (fewest lines of code changed) that I see.
I have a program see below
I made the method but I want to display it in the console
and not on the easy way like console.writeline(str.length). I want using the method I made.
could someone help me please
thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "dit is een test 1,2,3";
Console.WriteLine(str);
}
public int CountAllNumbersAndChar(string str)
{
return str.Length;
}
}
}
Update:
I have the following program now
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "this is a test 1,2,3";
int length = CountAllNumbersAndChar(str);
Console.WriteLine(str);
Console.WriteLine(length);// met de methode maar kan handiger met onderstaand voor beeld
// Console.WriteLine(str.Length);
// int numbers = str.Count(Char.IsNumber); // de makelijkste makelijke manier
//Console.WriteLine(numbers);
int countnumber = CountNumbers(str) ;
Console.WriteLine(countnumber);
int countwords = words(str);
Console.WriteLine(countwords);
}
public static int CountAllNumbersAndChar(string str)
{
return str.Length;
}
public static int CountNumbers(string str)
{
return str.Count(Char.IsNumber);
}
public static int words(string str)
{
int words = str.Split().Count(str => str.All(Char.IsLetter));
}
}
}
but it still doesnt work
could someone say me what I have to change ?
Is this what you want?
Console.WriteLine(CountAllNumbersAndChar(str));
Here's how you do it. Note public static int CountAllNumbersAndChar(string str) in the code below. You can't call CountAllNumbersAndChar from Main if you don't declare it as static.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "this is a test 1,2,3";
int length = CountAllNumbersAndChar(str);
Console.WriteLine(length);
}
public static int CountAllNumbersAndChar(string str)
{
return str.Length;
}
}
}
You could use LINQ for all these tasks. Although I'm not sure you are familiar with it. It's really simple though, so have a look at the code and see if you can follow.
string str = "dit is een test 1,2,3";
// Length of the string
int chars = str.Length;
// LINQ: Count all characters that is a number
int numbers = str.Count(Char.IsNumber);
// LINQ: Split the string on whitespace and count the
// elements that contains only letters
int words = str.Split().Count(s => s.All(Char.IsLetter));
Console.WriteLine(chars); // -> 21
Console.WriteLine(numbers); // -> 3
Console.WriteLine(words); // -> 4
Of course, the way I'm counting words there is not perfect, but it should get you started. For more accurate ways you should google it as there are hundreds of examples out there.
I think you want to count number of numbers inside your string
public int CountAllNumbersAndChar(string str)
{
return str.Split(new char[]{' ',','},
StringSplitOptions.RemoveEmptyEntries).Count
(
x=>
{
int d;
return int.TryParse(x,out d);
}
);
}