String Functions in C#
The standard library’s System.String
class and System.Linq
namespace provide many useful string-related functions. Here are some examples to give you a sense of the available methods and functions.
using System;
using System.Linq;
class StringFunctions
{
// We create a shorthand for Console.WriteLine as we'll use it a lot below.
static Action<string, object> p = (s, o) => Console.WriteLine($"{s}{o}");
static void Main()
{
// Here's a sample of the methods available for strings.
// Since these are methods on the string object itself,
// we call them directly on the string. You can find more
// methods in the System.String class documentation.
p("Contains: ", "test".Contains("es"));
p("Count: ", "test".Count(c => c == 't'));
p("StartsWith:", "test".StartsWith("te"));
p("EndsWith: ", "test".EndsWith("st"));
p("IndexOf: ", "test".IndexOf("e"));
p("Join: ", string.Join("-", new[] { "a", "b" }));
p("Repeat: ", new string('a', 5));
p("Replace: ", "foo".Replace("o", "0"));
p("Replace: ", "foo".Replace("o", "0", 1, StringComparison.Ordinal));
p("Split: ", string.Join(", ", "a-b-c-d-e".Split('-')));
p("ToLower: ", "TEST".ToLower());
p("ToUpper: ", "test".ToUpper());
}
}
When you run this program, you’ll see:
$ dotnet run
Contains: True
Count: 2
StartsWith:True
EndsWith: True
IndexOf: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: a, b, c, d, e
ToLower: test
ToUpper: TEST
This example demonstrates various string operations in C#. Note that some methods, like Contains
, StartsWith
, and EndsWith
, are called directly on string objects. Others, like Join
and Split
, are static methods of the string
class. The Count
method uses LINQ, which provides powerful querying capabilities for collections, including strings.
C# provides a rich set of string manipulation methods, making it easy to perform common operations on strings efficiently.