String in C Sharp

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

C# string tutorial Strings are collections of characters. The C# language introduces the string type.

This type allows us to manipulate character data through methods and properties. It provides methods to concatenate, append, replace, search and split. Consider a string of characters. A string is a class that holds characters and provides operations such as subscripting, concatenation, and comparison that we usually associated with the notion of a "string." Literals In this program we see how a string is created. It is assigned to a string literal "dot". Then another string literal is appended to that string. Finally a method on the string type is called to manipulate the strings again.

Program that uses string type: C#


using System;

class Program { static void Main() { string value = "orange"; value += "mango"; string result = string.Concat(value, "apple"); Console.WriteLine(result); } } Output >> orangemangoapple.

C# Split

Split separates strings. Strings often have delimiter characters in their data. Delimiters include "\r\n" newline sequences and the comma and tab characters. Split handles splitting upon string and character delimiters.

Tip: Use Split to separate parts from a string. If your input is "A B C", split on the space to get an array of: "A" "B" "C".

Array Example To begin, let's examine the simplest Split method overload. You already know the general way to do this, but it is good to see the basic syntax. This program splits on a single character. The array returned has four elements.

Char Program that splits on spaces [C#]

using System;

class Program { static void Main() { string s = "there is a cat"; // // Split string on spaces. // ... This will separate all the words. // string[] words = s.Split(' ');

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

Output

there is a cat breaking down directory path using System;

class Program { static void Main() { // The directory from Windows const string dir = @"C:\Users\Sam\Documents\Perls\Main"; // Split on directory separator string[] parts = dir.Split('\\'); foreach (string part in parts) { Console.WriteLine(part); } }

Output

C: Users Sam Documents Perls Main

You might also like