Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. string.Replace() / Contains()

string.Replace() / Contains()

The Replace() method replaces a substring, Contains() checks whether a string contains a specified value, and StartsWith() / EndsWith() check whether a string begins or ends with a specified value.

Syntax

// Returns a new string with all occurrences of oldValue replaced by newValue.
string.Replace(string oldValue, string newValue)

// Returns true if the string contains value.
string.Contains(string value)

// Returns true if the string starts with value.
string.StartsWith(string value)

// Returns true if the string ends with value.
string.EndsWith(string value)

Method list

MethodDescription
Replace(string oldValue, string newValue)Returns a new string with all occurrences of oldValue replaced by newValue.
Contains(string value)Returns true if the string contains value; otherwise, false.
StartsWith(string value)Returns true if the string starts with value.
EndsWith(string value)Returns true if the string ends with value.

Sample code

using System;

string sentence = "C# is an object-oriented programming language. C# was developed by Microsoft.";

// Use Replace() to substitute all occurrences.
string replaced = sentence.Replace("C#", "C-Sharp");
Console.WriteLine(replaced);
// C-Sharp is an object-oriented programming language. C-Sharp was developed by Microsoft.

// Use Contains() to check for a substring.
Console.WriteLine(sentence.Contains("Microsoft")); // True
Console.WriteLine(sentence.Contains("Java"));      // False

// Use StartsWith() / EndsWith() to check the beginning and end of a string.
string url = "https://wp-p.info";
Console.WriteLine(url.StartsWith("https")); // True
Console.WriteLine(url.EndsWith(".info"));   // True
Console.WriteLine(url.EndsWith(".com"));    // False

// Use Replace() to remove characters by replacing them with an empty string.
string noSpaces = "Hello, C# World!".Replace(" ", "");
Console.WriteLine(noSpaces); // Hello,C#World!

Notes

All of these methods are case-sensitive. To perform a case-insensitive comparison, pass StringComparison.OrdinalIgnoreCase as an argument, or normalize the string first using ToUpper() / ToLower().

Because C# strings are immutable, Replace() does not modify the original string — it returns a new one. Make sure to assign the return value to a variable.

To split or join strings, see Split() / string.Join().

If you find any errors or copyright issues, please .