devstory

Le Tutoriel de C# String et de StringBuilder

View more Tutorials:

Site d'apprentissage des langues gratuit:
Suivez-nous sur notre fanpage pour recevoir des notifications chaque fois qu'il y a de nouveaux articles. Facebook

1- Héritage hiérarchique

Quand vous travaillez avecdes données textuelles, CSharp vous fournit 2 classes String et StringBuilder. Quand vous travaillez avec Big Data, vous devez utiliser StringBuilder pour optimiser l' efficacité. Les 2 classes ont fondamentalement des points similaires.
  • String est immuable  (immutable)(ce concept va être détailler dans ce document). String ne permet pas l'existance des sous- classes.
  • StringBuilder est muable (mutable)

2- Concepts muable & immuable

Observez une illustration:
MutableClassExample.cs

namespace StringTutorial
{
    // Ceci est une classe qui a un champ: 'Value'.
    // Si vous avez un objet de cette classe.
    // Vous pouvez affecter une nouvelle valeur au champ 'Valeur'
    // via la méthode SetNewValue (int).
    // Donc, c'est une classe mutable (mutable).
    class MutableClassExample
    {
        private int Value;

        public MutableClassExample(int value)
        {
            this.Value = value;
        }

        public void SetNewValue(int newValue)
        {
            this.Value = newValue;
        }
    }

}
ImmutableClassExample.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    // Cette classe a 2 champs (field) : 'Value' & 'Name'.
    // Si vous avez un objet de cette classe,
    // Vous ne pouvez pas assigner une nouvelle valeur à 'Valeur', champ 'Name' de l'extérieur,
    // Cela signifie que cette classe est immuable (immutable)
    class ImmutableClassExample
    {
        private int Value;
        private String Name;

        public ImmutableClassExample(String name, int value)
        {
            this.Value = value;
            this.Name = name;
        }

        public String GetName()
        {
            return Name;
        }

        public int GetValue()
        {
            return Value;
        }
    }
}
String est une classe immuable (immutable), String comprend beaucoup de champs (field), par exemple Length,... mais des valeurs dans ces champs ne changent pas.

3- String et string

Dans C#, parfois vous trouvez que String et string sont utilisés en parallèle. En réalité, elles n'ont pas de différence, string peut être considérée comme un pseudonyme (alias) de System.String (le nom complet comprenant l'espace- nom de la classe String).

La table ci- dessous décrit la liste entière des pseudonyme des classes courantes.
 
Alias Class
object System.Object
string System.String
bool System.Boolean
byte System.Byte
sbyte System.SByte
short System.Int16
ushort System.UInt16
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
float System.Single
double System.Double
decimal System.Decimal
char System.Char

4- String

String est une classe cruciale de CSharp, et toute personne qui commence avec le programmme CSharp doit utiliser l'instruction Console.WriteLine() afin d'imprimer une String sur l'écran de Console. Beaucoup de débutants C# ne sont pas concients que String est immuable (immutable) et est fermée (Ne permet pas d'avoir de sous- classes), Chaque changement sur String dont le résultat est la création un nouveau objet String.
** String **

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class String : IComparable, ICloneable, IConvertible,
    IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>

4.1- Les méthodes de String

Vous pouvez examiner les méthodes de String à:
Ci-dessous sont des méthodes générales de String.
Some String methods

public bool EndsWith(string value)

public bool EndsWith(string value, StringComparison comparisonType)

public bool Equals(string value)

public int IndexOf(char value)

public int IndexOf(char value, int startIndex)

public int IndexOf(string value, int startIndex, int count)

public int IndexOf(string value, int startIndex, StringComparison comparisonType)

public int IndexOf(string value, StringComparison comparisonType)

public string Insert(int startIndex, string value)

public int LastIndexOf(char value)

public int LastIndexOf(char value, int startIndex)

public int LastIndexOf(char value, int startIndex, int count)

public int LastIndexOf(string value)

public int LastIndexOf(string value, int startIndex)

public int LastIndexOf(string value, int startIndex, int count)

public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType)

public int LastIndexOf(string value, int startIndex, StringComparison comparisonType)

public int LastIndexOf(string value, StringComparison comparisonType)

public int LastIndexOfAny(char[] anyOf)

public int LastIndexOfAny(char[] anyOf, int startIndex)

public int LastIndexOfAny(char[] anyOf, int startIndex, int count)

public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType)

public string Replace(char oldChar, char newChar)

public string Replace(string oldValue, string newValue)

public string[] Split(params char[] separator)

public string[] Split(char[] separator, int count)

public string[] Split(char[] separator, int count, StringSplitOptions options)

public string[] Split(char[] separator, StringSplitOptions options)

public string[] Split(string[] separator, StringSplitOptions options)

public bool StartsWith(string value)

public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)

public bool StartsWith(string value, StringComparison comparisonType)

public string Substring(int startIndex)

public string Substring(int startIndex, int length)

public char[] ToCharArray()

public char[] ToCharArray(int startIndex, int length)

public string ToLower()

public string ToLower(CultureInfo culture)

public string ToLowerInvariant()

public override string ToString()

public string ToUpper()

public string ToUpper(CultureInfo culture)

public string ToUpperInvariant()

public string Trim()

public string Trim(params char[] trimChars)

public string TrimEnd(params char[] trimChars)

public string TrimStart(params char[] trimChars)

 

4.1.1- Length

Length est une propriété de string, elle renvoie le nombre des caractères (Unicode) dans ce string.
LengthDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class LengthDemo
    {
        public static void Main(string[] args)
        {
            String str = "This is text";

            // Length est une Property (propriété) de la chaîne.
            // C'est la longueur de la chaîne (le nombre de caractères de cette chaîne).
            int len = str.Length;

            Console.WriteLine("String Length is : " + len);

            Console.Read();
        }
    }
}
Les résultats de l'exécution de l'exemple:

String Length is : 12

4.1.2- Concat(...)

Concat est une méthode statique qui est utilisée de concaténer (concatenate) plusieurs strings et renvoie une nouvelle String.
ConcatDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class ConcatDemo
    {
        public static void Main(string[] args)
        {
            string s1 = "One";
            string s2 = "Two";
            string s3 = "Three";

            // Pareil comme s1 + s2;
            string s = String.Concat(s1, s2); 

            Console.WriteLine("Concat s1, s2 : " + s);

            // Similaire comme s1 + s2 + s3;
            s = String.Concat(s1, s2, s3);

            Console.WriteLine("Concat s1, s2, s3 : " + s);

            Console.Read();
        }
    }


}
Les résultats de l'exécution de l'exemple:

Concat s1, s2 : OneTwo
Concat s1, s2, s3: OneTwoThree

4.1.3- IndexOf(..)

IndexOf(..) est une méthode qui renvoie l'index de positionnement qui est apparu pour la première fois un caractère précis ou une sous- string spécifiée dans la string actuelle. Il y a 8 méthodes IndexOf mais de différent paramètres. L'index commence de 0 (Pas 1).
IndexOfDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class IndexOfDemo
    {
        public static void Main(string[] args)
        {
            String str = "This is text";

            // Trouvez l'index (index) qui apparait le premier caractère 'i'.
            int idx = str.IndexOf('i'); // ==> 2
            Console.WriteLine("- IndexOf('i') = " + idx);

            // Trouvez l'index (index) dans cette chaîne de la première occurrence 'i'
            // lancez la recherche à l'index 4.
            idx = str.IndexOf('i', 4); // ==> 5
            Console.WriteLine("- indexOf('i',4) = " + idx);

            // Trouvez l'index (index) dans cette chaîne de la première occurrence de "te".
            idx = str.IndexOf("te"); // ==> 8
            Console.WriteLine("- IndexOf('te') = " + idx);

            Console.Read();
        }
    }

}
Results of running the example:

- IndexOf('i') = 2
- IndexOf('i',4) = 5
- IndexOf('te') = 8

4.1.4- Substring(..)

SubstringDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class SubstringDemo
    {
        public static void Main(string[] args)
        {
            string str = "This is text";

            // Renvoie la sous-chaîne de l'index 3 à la fin de la chaîne.
            string substr = str.Substring(3);

            Console.WriteLine("- Substring(3)=" + substr);

            // Renvoie la sous-chaîne à partir de l'index 2 et de la longueur 7.
            substr = str.Substring(2, 7);

            Console.WriteLine("- Substring(2, 7) =" + substr);


            Console.Read();
        }
    }

}
Les résultats de l'exécution de l'exemple:

- Substring(3)=s is text
- Substring(2, 7)=is is t

4.1.5- Replace(...)

Replace(..): Remplace toutes sous- strings par une autre sous- string de la String courante et renvoie une nouvelle string.
ReplaceDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class ReplaceDemo
    {
        public static void Main(string[] args)
        {
            String str = "This is text";

            // Remplacez le caractère 'i' par 'x'.
            String s2 = str.Replace('i', 'x');

            Console.WriteLine("- s2=" + s2);// ==> "Thxs xs text".

            // Remplacez toutes les sous-chaînes correspondant à "is" par "abc".
            String s3 = str.Replace("is", "abc");

            Console.WriteLine("- s3=" + s3);// ==> "Thabc abc text".

            // Remplacez la première sous-chaîne de cette chaîne qui correspond à "is" par "abc".
            String s4 = ReplaceFirst(str, "is", "abc");

            Console.WriteLine("- s4=" + s4);// ==> "Thabc is text".

            Console.Read();
        }

        // Remplacez la première sous-chaîne par une nouvelle sous-chaîne.
        static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);
            if (pos < 0)
            {
                return text;
            }
            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

}
Les résultats de l'exécution de l'exemple:

- s2=Thxs xs text
- s3=Thabc abc text
- s4=Thabc is text

4.1.6- Des autres exemples:

StringOtherDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class StringOtherDemo
    {
        public static void Main(string[] args)
        {
            String str = "This is text";

            Console.WriteLine("- str=" + str);

            // Renvoyez la chaîne en minuscule (lower case string).
            String s2 = str.ToLower();

            Console.WriteLine("- s2=" + s2);

            // Renvoyez la chaîne en majuscule (upper case string).
            String s3 = str.ToUpper();

            Console.WriteLine("- s3=" + s3);

            // Vérifier la chaîne commencée par "This" ou non.
            bool swith = str.StartsWith("This");

            Console.WriteLine("- 'str' startsWith This ? " + swith);

            // Une chaîne avec des espaces en avant et en arrière.
            // Note: \t est un caractère de tabulation
            // \n est un nouveau caractère de ligne
            str = " \t CSharp is hot!  \t \n ";

            Console.WriteLine("- str=" + str);

            // Renvoyez une copie de la chaîne, les espaces de début et de fin étant omis.
            String s4 = str.Trim();

            Console.WriteLine("- s4=" + s4);

            Console.Read();
        }
    }

}
Les résultats de l'exécution de l'exemple:

- str=This is text
- s2=this is text
- s3=THIS IS TEXT
- 'str' startsWith This ? True
- str=   Csharp is hot!

- s4=CSharp is hot!

5- StringBuilder

Dans C#, le résultat de chaque modification dans String est la création un nouveau objet String. Alors que StringBuilder comprend une multitude de caractères, cette gamme va être automatiquement remplacée par une autre plus étendue s'il est nécessaire, et copier les caractères depuis l'ancienne gamme. Si vous devez concaténer une multiple de strings, vous devez utiliser StringBuilder, il aide à augmenter l'efficacité du programme. Mais il n'est pas nécessaire si vous concaténez seulement quelques stringss, n'abusez pas de StringBuilder dans ce cas. 
StringBuilderDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringTutorial
{
    class StringBuilderDemo
    {
        public static void Main(string[] args)
        {

            // Créez un objet StringBuilder
            // d'une capacité (capacity) de 10 caractères.
            StringBuilder sb = new StringBuilder(10);

            // Ajoutez la chaîne Hello.
            sb.Append("Hello...");
            Console.WriteLine("- sb after appends a string: " + sb);

            // Ajoutez un caractère
            char c = '!';
            sb.Append(c);
            Console.WriteLine("- sb after appending a char: " + sb);

            // Insérez une chaîne à l'index 5.
            sb.Insert(8, " CSharp");
            Console.WriteLine("- sb after insert string: " + sb);

            // Supprimez la sous-chaîne aux index 5 et 3 caractères.
            sb.Remove(5, 3);

            Console.WriteLine("- sb after remove: " + sb);

            // Obtenez une chaîne dans StringBuilder.
            String s = sb.ToString();

            Console.WriteLine("- String of sb: " + s);

            Console.Read();
        }
    }

}
Les résultats de l'exécution de l'exemple:

- sb after appends a string: Hello...
- sb after appending a char: Hello...!
- sb after insert string: Hello... CSharp!
- sb after remove: Hello CSharp!
- String of sb: Hello CSharp!

View more Tutorials: