« String » : différence entre les versions
Apparence
(10 versions intermédiaires par le même utilisateur non affichées) | |||
Ligne 39 : | Ligne 39 : | ||
"""; | """; | ||
// Any whitespace to the left of the closing double quotes will be removed from the string literal | // Any whitespace to the left of the closing double quotes will be removed from the string literal | ||
var namePropertyName = "Name"; | |||
var namePropertyValue = "Nicolas"; | |||
var json = /*lang=json,strict*/ $$""" | |||
{ | |||
"id": "123456789", | |||
"{{namePropertyName}}": "{{namePropertyValue}}" | |||
} | |||
"""; | |||
</kode> | </kode> | ||
Ligne 72 : | Ligne 81 : | ||
// case insensitive | // case insensitive | ||
string1.Contains(string2, StringComparison.CurrentCultureIgnoreCase)) | string1.Contains(string2, StringComparison.CurrentCultureIgnoreCase)); | ||
// case and accent insensitive | // case and accent insensitive | ||
Ligne 94 : | Ligne 103 : | ||
var ss = s.Substring(1); // 123456789 keep from index 1 until the end | var ss = s.Substring(1); // 123456789 keep from index 1 until the end | ||
var ss = s.Remove(0, 1); // 123456789 remove from index 0 to the next character | var ss = s.Remove(0, 1); // 123456789 remove from index 0 to the next character | ||
var ss = s[1..]; | |||
// remove last character | // remove last character | ||
var ss = s.Substring(0, s.Length - 1); // 012345678 keep from index 0 until the before last character | var ss = s.Substring(0, s.Length - 1); // 012345678 keep from index 0 until the before last character | ||
var ss = s.Remove(s.Length - 1); // 012345678 remove from the before last character to the end | var ss = s.Remove(s.Length - 1); // 012345678 remove from the before last character to the end | ||
var ss = s[..^1]; | |||
// from index 5 to the next 2 characters | // from index 5 to the next 2 characters | ||
Ligne 108 : | Ligne 119 : | ||
</kode> | </kode> | ||
== [http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx Format] == | == [http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx Numeric Format] == | ||
<kode lang=csharp> | <kode lang=csharp> | ||
double d = 1234.567; | double d = 1234.567; | ||
d.ToString("n"); // 1 234,57 | |||
$"{d:n}"; // 1 234,57 | |||
d.ToString("n0"); // 1 235 | |||
d.ToString("c1"); // 1 234,6 € | |||
d.ToString("p2"); // 123 456.70 % | |||
CultureInfo CultureUS = new CultureInfo("en-US", false); | CultureInfo CultureUS = new CultureInfo("en-US", false); | ||
Ligne 121 : | Ligne 133 : | ||
string s1 = d.ToString("00"); // 1234 | string s1 = d.ToString("00"); // 1234 | ||
string s2 = | string s2 = d.ToString("00000"); // 01235 | ||
// remove trailing zeros | |||
1234.5670.ToString("0.###"); // 1234.567 | |||
</kode> | </kode> | ||
{{warn | L'arrondit avec N se fait vers le nombre supérieur. Ex: 0.5 → 1<br> | {{warn | L'arrondit avec N se fait vers le nombre supérieur. Ex: 0.5 → 1<br> | ||
Ligne 237 : | Ligne 252 : | ||
public static class StringExtension | public static class StringExtension | ||
{ | { | ||
public static string FirstCharToUpper(this string input) => | private static readonly CultureInfo invariantCulture = CultureInfo.InvariantCulture; | ||
public static string FirstCharToUpper(this string input) | |||
=> input switch | |||
{ | { | ||
null => throw new ArgumentNullException(nameof(input)), | null => throw new ArgumentNullException(nameof(input)), | ||
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)), | "" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)), | ||
_ => input | _ => input[0].ToString().ToUpper(invariantCulture) + input[1..].ToLower(invariantCulture) | ||
}; | }; | ||
} | } |
Dernière version du 20 février 2025 à 15:15
À savoir
String est un type ref qui se comporte comme un type value.
Il est immuable, toute modification créé un nouveau string
Interpolation de chaînes
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}";
// équivalent à
string s = string.Format("Bonjour {0}, nous sommes le {1:D}", user.Name, DateTime.Today);
// forcer le formattage en culture invariente (en-US)
string s = FormattableString.Invariant($"Un chiffre avec un point: {MyDouble}");
// échapper les accolades / curly brackets
string s = $"Bonjour {user.Name}, curly brackets: open {{ close }}";
|
Verbatim string literal
// permet de ne pas avoir à échapper les caractères spéciaux
var s1 = @"le backslash: \";
var s0 = "le backslash: \\";
// échapper le double quote
var s2 = @"le double quote: """;
|
Raw string literals
Arbitrary text including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences.
var raw = $"""
line 1
{i}
line "2"
""";
// Any whitespace to the left of the closing double quotes will be removed from the string literal
var namePropertyName = "Name";
var namePropertyValue = "Nicolas";
var json = /*lang=json,strict*/ $$"""
{
"id": "123456789",
"{{namePropertyName}}": "{{namePropertyValue}}"
}
""";
|
String et tableaux
Transformer une liste d'éléments en string avec séparateurs
// avec une List
String.Join(",", new List<string>() { "a", "b" });
// en utilisant params et avec des doubles
String.Join(";", 1, 2);
// avec un ArrayList
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
// test if string1 contains string2
string1.Contains(string2);
// case insensitive
string1.Contains(string2, StringComparison.CurrentCultureIgnoreCase));
// case and accent insensitive
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";
// remove first character
var ss = s.Substring(1); // 123456789 keep from index 1 until the end
var ss = s.Remove(0, 1); // 123456789 remove from index 0 to the next character
var ss = s[1..];
// remove last character
var ss = s.Substring(0, s.Length - 1); // 012345678 keep from index 0 until the before last character
var ss = s.Remove(s.Length - 1); // 012345678 remove from the before last character to the end
var ss = s[..^1];
// from index 5 to the next 2 characters
var ss = s.Substring(5); // 56789
var ss = s.Substring(5, 2); // 56
// remove from index 5 to the next 2 characters
var ss = s.Remove(5); // 01234
var ss = s.Remove(5, 2); // 01234789
|
Numeric Format
double d = 1234.567;
d.ToString("n"); // 1 234,57
$"{d:n}"; // 1 234,57
d.ToString("n0"); // 1 235
d.ToString("c1"); // 1 234,6 €
d.ToString("p2"); // 123 456.70 %
CultureInfo CultureUS = new CultureInfo("en-US", false);
string s4 = d.ToString("N", CultureUS); // 1,234.57
string s1 = d.ToString("00"); // 1234
string s2 = d.ToString("00000"); // 01235
// remove trailing zeros
1234.5670.ToString("0.###"); // 1234.567
|
![]() |
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). |
Afficher un entier dans différentes bases
// 10 en base 2
Convert.ToString(10, 2); // 1010
// 10 en base 16
Convert.ToString(10, 16); // a
string.Format("{0:x}", 10); // a
10.ToString("X"); // A
// a en base 10
Convert.ToInt32("a", 16); // 10
int.Parse("a", NumberStyles.AllowHexSpecifier); // 10
|
![]() |
Seules les bases 2, 8, 10, et 16 sont acceptées. |
Distinct
string texte = "AABBB1111"
string distinctTexte = new String(texte.Distinct().ToArray());
|
Répétition de caractères
new String('a', 5); // aaaaa
|
Justifier un string
var s = "123";
var s1 = s.PadLeft(5, '-'); // --123
|
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, "?"));
// th? qu?ck br?wn f?x j?mps ?v?r th? l?z? d?g
|
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
{
/// <summary>
/// Gets the <see cref="T:System.Text.Encoding" /> in which the output is written.
/// It used to set the encoding in the first line file : <?xml version="1.0" encoding="utf-8"?>
/// </summary>
/// <returns>The Encoding in which the output is written.</returns>
public override Encoding Encoding
{
// UTF8Encoding(false) instead of Encoding.UTF8 to get utf-8 without BOM
get { return new UTF8Encoding(false); }
}
}
// sérialise en UTF8 sans BOM
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))
|
Guid
Guid.NewGuid().ToString(); // 88a773f1-f661-4257-bdb8-40115541d8be
Guid.NewGuid().ToString("N"); // 88a773f1f6614257bdb840115541d8be
|
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);
|