String

De Banane Atomic
Aller à la navigationAller à la recherche

À 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.

Csharp.svg
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

Csharp.svg
// 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: """;

String et tableaux

Transformer une liste d'éléments en string avec séparateurs

Csharp.svg
// 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

Csharp.svg
var monString = "1,2,3,4"
string[] result = monString.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);

Tests

Comparaison

Csharp.svg
string1.Equals(string2, StringComparison.OrdinalIgnoreCase);

Contains

Csharp.svg
// 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

Csharp.svg
if (String.IsNullOrEmpty(monString)) { }

Manipulation

Sous-chaîne

Csharp.svg
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

// 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

// 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

Format

Csharp.svg
double d = 1234.567;

string s1 = d.ToString("N"); // 1 234,57
string s1 = $"{d:N}";        // 1 234,57
string s2 = n.ToString("N0"); // 1 235
string s3 = n.ToString("N1"); // 1 234,6

CultureInfo CultureUS = new CultureInfo("en-US", false);
string s4 = d.ToString("N", CultureUS); // 1,234.57

string s1 = d.ToString("00"); // 1234
string s2 = n.ToString("00000"); // 01235
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);

Afficher un entier dans différentes bases

Csharp.svg
// 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.

Codes des caractères

Distinct

Csharp.svg
string texte = "AABBB1111"
string distinctTexte = new String(texte.Distinct().ToArray());

Répétition de caractères

Csharp.svg
new String('a', 5); // aaaaa

Justifier un string

Csharp.svg
var s = "123";
var s1 = s.PadLeft(5, '-'); // --123

Remplacer les caractères provenant d'un tableau

Csharp.svg
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

Csharp.svg
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

Csharp.svg
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

Csharp.svg
int i;
if (int.TryParse("1", out i))

Convert a String to a Number

Guid

Csharp.svg
Guid.NewGuid().ToString();     // 88a773f1-f661-4257-bdb8-40115541d8be
Guid.NewGuid().ToString("N");  // 88a773f1f6614257bdb840115541d8be

Premier caractère en majuscule / capitalize first character

StringExtension.cs
public static class StringExtension
{
    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.First().ToString().ToUpper() + input.Substring(1)
        };
}
Cs.svg
if (String.IsNullOrEmpty(monString))
{
    return String.Empty;
}

return Char.ToUpper(monString[0]) + monString.Substring(1);