Getting started with C# LanguageVerbatim StringsOperatorsExtension MethodsCollection InitializersString InterpolationC# 6.0 FeaturesConstructors and FinalizersKeywordsGenericsReflectionInheritanceNull-Coalescing OperatorUsing StatementString Escape SequencesException HandlingNull-conditional OperatorsBuilt-in TypesLambda expressionsAsync-AwaitPropertiesThreadingUsing DirectiveMethodsYield KeywordEventsLINQ QueriesCommon String OperationsExpression TreesOverload ResolutionString.Formatnameof OperatorUnsafe Code in .NETInitializing PropertiesBindingList<T>ILGeneratorObject initializersXML Documentation CommentsPreprocessor directivesDynamic typeAnonymous typesStructsTuplesEnumAccess ModifiersTask Parallel LibraryAttributesGuidSingleton ImplementationDelegatesNullable typesGarbage Collector in .NetNetworkingArraysEquality OperatorLock StatementAction FiltersXmlDocument and the System.Xml namespaceDateTime MethodsBackgroundWorkerPolymorphismStatic ClassesIndexerIDisposable interfaceAliases of built-in typesImmutabilityXDocument and the System.Xml.Linq namespaceC# 7.0 FeaturesPerforming HTTP requestsGenerating Random Numbers in C#LoopingNamed ArgumentsDiagnosticsInterfacesIEnumerableNaming ConventionsAn overview of c# collectionsChecked and UncheckedRecursionFunctional ProgrammingLiteralsCastingNullReferenceExceptionFunc delegatesLINQ to XMLHash FunctionsHandling FormatException when converting string to other typesCryptography (System.Security.Cryptography)INotifyPropertyChanged interfaceValue type vs Reference typeC# 4.0 FeaturesIQueryable interfaceTask Parallel Library (TPL) Dataflow ConstructsStreamRuntime CompileConditional StatementsInteroperabilityOverflowEquals and GetHashCodeType ConversionParallel LINQ (PLINQ)String ManipulationString ConcatenatePartial class and methodsStopwatchesRegex ParsingC# ScriptC# 3.0 FeaturesAsync/await, Backgroundworker, Task and Thread ExamplesTimersFunction with multiple return valuesBinary SerializationMaking a variable thread safeIComparableCode ContractsIteratorsAssemblyInfo.cs ExamplesFile and Stream I/OCode Contracts and AssertionsCachingC# 5.0 FeaturesImplementing Flyweight Design PatternStringBuilderImplementing Decorator Design PatternAccessing DatabasesT4 Code GenerationMicrosoft.Exchange.WebServices.NET Compiler Platform (Roslyn)Data AnnotationUsing SQLite in C#System.Management.AutomationFileSystemWatcherSystem.DirectoryServices.Protocols.LdapConnectionNamed and Optional ArgumentsComments and regionsC# Authentication handlerPointers & Unsafe CodePointersHow to use C# Structs to create a Union type (Similar to C Unions)BigIntegerDependency InjectionReactive Extensions (Rx)Creational Design PatternsCreating a Console Application using a Plain-Text Editor and the C# Compiler (csc.exe)Reading and writing .zip filesGeneric Lambda Query BuilderImport Google ContactsLambda ExpressionsCLSCompliantAttributeObservableCollection<T>Synchronization Context in Async-AwaitICloneableRead & Understand StacktracesLinq to ObjectsASP.NET IdentityAccess network shared folder with username and passwordAsynchronous SocketStructural Design PatternsO(n) Algorithm for circular rotation of an arrayCreating Own MessageBox in Windows Form ApplicationIncluding Font ResourcesObject Oriented Programming In C#Using json.netGetting Started: Json with C#Windows Communication Foundation

String Manipulation

Other topics

Changing the case of characters within a String

The System.String class supports a number of methods to convert between uppercase and lowercase characters in a string.

Note: The reason to use the invariant versions of these methods is to prevent producing unexpected culture-specific letters. This is explained here in detail.

Example:

string s = "My String";
s = s.ToLowerInvariant(); // "my string"
s = s.ToUpperInvariant(); // "MY STRING"

Note that you can choose to specify a specific Culture when converting to lowercase and uppercase by using the String.ToLower(CultureInfo) and String.ToUpper(CultureInfo) methods accordingly.

Finding a string within a string

Using the System.String.Contains you can find out if a particular string exists within a string. The method returns a boolean, true if the string exists else false.

string s = "Hello World";
bool stringExists = s.Contains("ello");  //stringExists =true as the string contains the substring 

Using the System.String.IndexOf method, you can locate the starting position of a substring within an existing string.
Note the returned position is zero-based, a value of -1 is returned if the substring is not found.

string s = "Hello World";
int location = s.IndexOf("ello"); // location = 1

To find the first location from the end of a string, use the System.String.LastIndexOf method:

string s = "Hello World";
int location = s.LastIndexOf("l"); // location = 9

Removing (Trimming) white-space from a string

The System.String.Trim method can be used to remove all leading and trailing white-space characters from a string:

string s = "     String with spaces at both ends      ";
s = s.Trim(); // s = "String with spaces at both ends"

In addition:

Substring to extract part of a string.

The System.String.Substring method can be used to extract a portion of the string.

string s ="A portion of word that is retained";
s=str.Substring(26);  //s="retained"

s1 = s.Substring(0,5);  //s="A por"

Replacing a string within a string

Using the System.String.Replace method, you can replace part of a string with another string.

string s = "Hello World";
s = s.Replace("World", "Universe"); // s = "Hello Universe"

All the occurrences of the search string are replaced:

string s = "Hello World";
s = s.Replace("l", "L"); // s = "HeLLo WorLD"

String.Replace can also be used to remove part of a string, by specifying an empty string as the replacement value:

string s = "Hello World";
s = s.Replace("ell", String.Empty); // s = "Ho World"

Splitting a string using a delimiter

Use the System.String.Split method to return a string array that contains substrings of the original string, split based on a specified delimiter:

string sentence = "One Two Three Four";
string[] stringArray = sentence.Split(' ');

foreach (string word in stringArray)
{
    Console.WriteLine(word);    
}

Output:

One
Two
Three
Four

Concatenate an array of strings into a single string

The System.String.Join method allows to concatenate all elements in a string array, using a specified separator between each element:

string[] words = {"One", "Two", "Three", "Four"};
string singleString = String.Join(",", words); // singleString = "One,Two,Three,Four"

String Concatenation

String Concatenation can be done by using the System.String.Concat method, or (much easier) using the + operator:

string first = "Hello ";
string second = "World";

string concat = first + second; // concat = "Hello World"
concat = String.Concat(first, second); // concat = "Hello World"

Contributors

Topic Id: 3599

Example Ids: 12402,13639,13640,13641,13642,13643,13644

This site is not affiliated with any of the contributors.