Metody stringów: klasa TextTools

Klasy i obiekty - Podstawy C# (csharp)

Typ string ma wiele gotowych metod: ToUpper, Contains, IndexOf, Substring, Replace, Split. Napisy są niezmienne - każda z tych metod zwraca NOWY napis, a oryginał zostaje. Odwrócenie tekstu robimy przez tablicę znaków ToCharArray() i Array.Reverse. Pojedynczy znak napisu odczytujemy indeksem text[i], a znak zapisujemy w apostrofach: 'a'.
using System;

class TextTools
{
  public static string Reverse(string input)
  {
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new string(chars);
  }

  public static int CountOccurrences(string input, char character)
  {
    int count = 0;
    for (int i = 0; i < input.Length; i++)
    {
      if (input[i] == character)
      {
        count++;
      }
    }
    return count;
  }
}

class Program
{
  static void Main(string[] args)
  {
    string text = "Programowanie w C# jest fajne";
    Console.WriteLine($"Długość: {text.Length}");
    Console.WriteLine($"Wielkie litery: {text.ToUpper()}");
    Console.WriteLine($"Odwrócony: {TextTools.Reverse(text)}");
    Console.WriteLine($"Liczba liter 'a': {TextTools.CountOccurrences(text, 'a')}");
    Console.WriteLine($"Zawiera \"C#\": {text.Contains("C#")}");
    Console.WriteLine($"Pozycja \"jest\": {text.IndexOf("jest")}");
    Console.WriteLine($"Pierwsze 13 znaków: {text.Substring(0, 13)}");
    Console.WriteLine($"Zamiana: {text.Replace("fajne", "super")}");
    string[] words = text.Split(' ');
    Console.WriteLine($"Słów: {words.Length}, ostatnie: {words[words.Length - 1]}");
    Console.WriteLine($"Oryginał bez zmian: {text}");
  }
}

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.