À savoir
String est un type ref qui se comporte comme un type value.
Il est immuable, toute modification créé un nouveau string
Le préfixe $ devant la chaîne indique qu'il s'agit d'une chaîne interpolée.
|
string s = $"Bonjour {user.Name}, nous sommes le {DateTime.Today:D}";
string s = string.Format("Bonjour {0}, nous sommes le {1:D}", user.Name, DateTime.Today);
string s = FormattableString.Invariant($"Un chiffre avec un point: {MyDouble}");
string s = $"Bonjour {user.Name}, curly brackets: open {{ close }}";
|
Verbatim string literal
|
var s1 = @"le backslash: \";
var s0 = "le backslash: \\";
var s2 = @"le double quote: """;
|
Arbitrary text including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences.
|
var raw = $"""
line 1
{i}
line "2"
""";
var namePropertyName = "Name";
var namePropertyValue = "Nicolas";
var json = $$"""
{
"id": "123456789",
"{{namePropertyName}}": "{{namePropertyValue}}"
}
""";
|
String et tableaux
Transformer une liste d'éléments en string avec séparateurs
|
String.Join(",", new List<string>() { "a", "b" });
String.Join(";", 1, 2);
String.Join(";", myArrayList.ToArray());
|
Split
|
var monString = "1,2,3,4"
string[] result = monString.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
|
Tests
Comparaison
|
string1.Equals(string2, StringComparison.OrdinalIgnoreCase);
|
Contains
|
string1.Contains(string2);
string1.Contains(string2, StringComparison.CurrentCultureIgnoreCase));
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
string1,
string2,
CompareOptions.IgnoreNonSpace) > -1);
|
Test si null ou vide
|
if (String.IsNullOrEmpty(monString)) { }
|
Manipulation
Sous-chaîne
|
var s = "0123456789";
var ss = s.Substring(1);
var ss = s.Remove(0, 1);
var ss = s[1..];
var ss = s.Substring(0, s.Length - 1);
var ss = s.Remove(s.Length - 1);
var ss = s[..^1];
var ss = s.Substring(5);
var ss = s.Substring(5, 2);
var ss = s.Remove(5);
var ss = s.Remove(5, 2);
|
|
double d = 1234.567;
d.ToString("n");
$"{d:n}";
d.ToString("n0");
d.ToString("c1");
d.ToString("p2");
CultureInfo CultureUS = new CultureInfo("en-US", false);
string s4 = d.ToString("N", CultureUS);
string s1 = d.ToString("00");
string s2 = d.ToString("00000");
1234.5670.ToString("0.###");
|
 |
L'arrondit avec N se fait vers le nombre supérieur. Ex: 0.5 → 1
The result strings reflect numbers that are rounded away from zero (that is, using MidpointRounding.AwayFromZero).
Par défaut Math.Round arrondit au nombre inférieur. Ex: 0.5 → 0
Math.Round(nombre, MidpointRounding.ToEven); |
|
Convert.ToString(10, 2);
Convert.ToString(10, 16);
string.Format("{0:x}", 10);
10.ToString("X");
Convert.ToInt32("a", 16);
int.Parse("a", NumberStyles.AllowHexSpecifier);
|
 |
Seules les bases 2, 8, 10, et 16 sont acceptées. |
Codes des caractères
Distinct
|
string texte = "AABBB1111"
string distinctTexte = new String(texte.Distinct().ToArray());
|
Répétition de caractères
|
new String('a', 5);
|
Justifier un string
|
var s = "123";
var s1 = s.PadLeft(5, '-');
|
Remplacer les caractères provenant d'un tableau
|
string sentence = "the quick brown fox jumps over the lazy dog";
string[] charToReplace = { "a", "e", "i", "o", "u", "y" };
sentence = charToReplace.Aggregate(sentence,
(replacedSentence, currentCharToReplace) => replacedSentence.Replace(currentCharToReplace, "?"));
|
Unicode To Ascii
|
string unicodeContent;
var normalizedOutputBuilder = new StringBuilder();
foreach (char c in unicodeContent.Normalize(NormalizationForm.FormD))
{
var category = CharUnicodeInfo.GetUnicodeCategory(c);
if (category != UnicodeCategory.NonSpacingMark)
{
normalizedOutputBuilder.Append(c);
}
}
string asciiContent = normalizedOutputBuilder.ToString();
|
UTF8 StringWriter
|
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return new UTF8Encoding(false); }
}
}
string output;
using (var sw = new Utf8StringWriter())
{
var serializer = new XmlSerializer(monObjet.GetType());
serializer.Serialize(sw, monObjet, null);
output = sw.ToString();
}
|
Convertions
|
int i;
if (int.TryParse("1", out i))
|
Convert a String to a Number
Guid
|
Guid.NewGuid().ToString();
Guid.NewGuid().ToString("N");
|
Premier caractère en majuscule
StringExtension.cs
|
public static class StringExtension
{
private static readonly CultureInfo invariantCulture = CultureInfo.InvariantCulture;
public static string FirstCharToUpper(this string input)
=> input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => input[0].ToString().ToUpper(invariantCulture) + input[1..].ToLower(invariantCulture)
};
}
|
|
if (String.IsNullOrEmpty(monString))
{
return String.Empty;
}
return Char.ToUpper(monString[0]) + monString.Substring(1);
|