Topic : Strings in C# Programming Language: String Class Properties | String Class Methods:

What is String?

String such as "infoBrother" are Actually represented by C# as a Sequence of Characters in Memory. In Other words, a string is simply a character array. however, more common practice is to use the String keyword to declare a String Variable. The String keyword is an Alias for the System.String



  • Creating a String Object:

    We can Create String Object using one of the following Methods: » By Assigning a String Literal to a String Variable:
    » By Using a String Class Constructor:
    » By Using the String Concatenation Operator (+):
    » By Retrieving a Property or Calling a Method that Returns a String:
    » By Calling a Formatting method to convert a Value or an Object to its string representation.



In Above There are some methods to create a String object. let's have an Example here, where we will create a String object using these all Methods:



/*Example: Creating String Object: InfoBrother:*/

using System;

namespace myString
{
    class Program
    {
        static void Main(string[] args)
        {
            //By String Literal and concatenation:
            string first_name = "Sardar";
            string Last_name = " Omar";
            string fullName = first_name + Last_name;
            Console.WriteLine("Your Full Name is: " + fullName);


            //By using String Constructor:
            char[] letters = { 'G', 'o', 'o', 'd', ' ', 'L', 'u', 'c', 'k' };
            string wish = new string(letters);
            Console.WriteLine("Wish you :" + wish);

            //Method Returning a String:
            string[] sArray = { "Welcome"," ", "To"," ", "InfoBrother", ".com" };
            string message = string.Join("", sArray);
            Console.WriteLine("Message: {0} ", message);


            //By Formatting Methods :
            DateTime date = new DateTime(2017, 4, 21, 10, 27, 1);
            string tutorial = String.Format("was Written at {0:t} on {0:D}", date);
            Console.WriteLine("This Tutorial {0}", tutorial);

            Console.ReadKey();
        }
    }
}


Strings Class:

In C#, String is an object of System.string class that represent sequence of Characters. We can perform many Operations on strings such as Concatenation, Comparison, getting sub-string, search, trim, replacement etc.



Properties of String Class:

The Following Table Describes some of the Most Commonly used Properties of the String Class:


PropertyDescription:
chars[int32]Gets the Char Object at a specified Position in the Current String Object.
LengthGets the Number of Characters in the Current String Object.


Methods in String Class:

The Following Table Describes some of the Most Commonly used Methods of the String Class:


MethodDescription:
Clone();Returns a reference to this instance of String.
int Compare(StringX, StringY);Compares sub-strings of two specified String objects and returns an integer that indicates their relative position in the sort order.
int Compare(string StrX, String StrY, bool ignoreCase)Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.
CompareTo(Object)Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.
CompareTo(String)Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.
String Concat(String StrX, String StrY)Concatenates Two String Objects:
String Concat(String StrX, String StrY, String StrZ) Concatenates Three Strings Objects:
String Concat(String StrW ,StrX, String StrY, String StrZ) Concatenates Four Strings Objects:
Concat(String StrX[])Concatenates the string representations of the elements in a specified Object array.
contains(String Value)Returns a value indicating whether the specified String object occurs within this string.
Copy(String x)Creates a new instance of String with the same value as a specified String.
CopyTo(Int32, char[], int32, int32)Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.
EndsWith(String)Determines whether the end of this string instance matches the specified string.
Equals(String Value);Determines whether the current String object and the specified String object have the same value.
Equals(String x, String y)Determines whether two specified String objects have the same value.
Format(String Object)Replaces one or more format items in a specified string with the string representation of a specified object.
Format(String Object, Object)Replaces the format items in a specified string with the string representation of two specified objects.
Format(String Object[])Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
GetType()Gets the Type of the current instance.(Inherited from Object.)
GetTypeCode();Returns the TypeCode for class String.
IndexOf(Char);Reports the zero-based index of the first occurrence of the specified Unicode character in this string.
IndexOf(String);Reports the zero-based index of the first occurrence of the specified string in this instance.
IndexOfAny(Char[]);Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.
Insert(int32, String);Returns a new string in which a specified string is inserted at a specified index position in this instance.
intern(String);Retrieves the system's reference to the specified String.
IsInterned(String);Retrieves a reference to a specified String.
IsNormalized();Indicates whether this string is in Unicode normalization form C.
IsNullOrEmpty(String Value);Indicates whether the specified string is null or an Empty string.
IsNullOrWhiteSpace(String);Indicates whether a specified string is null, empty, or consists only of white-space characters.
Join(String, Object[]);Concatenates the elements of an object array, using the specified separator between each element.
Joint(String, String[]);Concatenates all the elements of a string array, using the specified separator between each element.
LastIndexOf(Char);Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.
LastIndexOf(String);Reports the zero-based index position of the last occurrence of a specified string within this instance.
LastIndexOfAny(Char[]);Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.
Normalize();Returns a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C.
Normalize(NormalizationForm);Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form.
Remove(int startIndex);Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
Remove(Int StartIndex, Int Count);Removes the specified number of characters in the current string beginning at a specified position and returns the string.
Replace(Char, Char);Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.
Replace(String, String);Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
Split(Char[]);Splits a string into substrings that are based on the characters in an array.
StartsWith(String);Determines whether the beginning of this string instance matches the specified string.
SubString(Int);Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
ToCharArray();Copies the characters in this instance to a Unicode character array.
ToLower();Returns a copy of this string converted to lowercase.
ToString();Returns this instance of String; no actual conversion is performed.
ToUpper():Returns a copy of this string converted to uppercase.
Trim();Removes all leading and trailing white-space characters from the current String object.


Example:

Let's have some example, where we will use some of the Above String Class Methods:



Clone();
/*Example: String Class Methods: InfoBrother:*/
using System;

namespace StringMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] array = { "web.","InfoBrother", ".com" };
            string[] cloned = array.Clone() as string[];

            Console.WriteLine(string.Join("", array));
            Console.WriteLine(string.Join("", cloned));
            Console.WriteLine();

            // Change the first element in the cloned array.
            cloned[0] = "www.";

            Console.WriteLine(string.Join("", array));
            Console.WriteLine(string.Join("", cloned));

            Console.ReadKey();
        }
    }
}


Compare();
/*Example: String Class Methods: InfoBrother:*/
using System;

namespace StringMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = "InfoBrother";
            string y = "infobrother"; //remember C# is Case Sensetive:

            if(string.Compare(x,y) == 0)
            {
                Console.WriteLine("{0} and {1} is Equal: ", x, y);
            }
            else
            {
                Console.WriteLine("{0} and {1} is Not Equal: ", x, y);
            }

            Console.ReadKey();
        }
    }
}



Compare(string, string, bool);
/*Example: String Class Methods: InfoBrother:*/
using System;

namespace StringMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create upper-case characters
            String stringUpper = "INFOBROTHER";

            // Create lower-case characters
            String stringLower = "infobrother";

            // Display the strings.
            Console.WriteLine("Comparing '{0}' and '{1}':",
                              stringUpper, stringLower);

            // Compare the uppercased strings; the result is true.
            Console.WriteLine("The Strings are equal when capitalized? {0}",
            String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0
                           ? "true" : "false");

            // Compare the uppercased strings; the result is true.
            Console.WriteLine("The Strings are equal when in Actual? {0}",
            String.Compare(stringUpper.ToUpper(), stringLower.ToLower()) == 0
                           ? "true" : "false");


            // The previous method call is equivalent to this
            //Compare method, which ignores case.
            Console.WriteLine("The Strings are equal when case is ignored? {0}",
            String.Compare(stringUpper, stringLower, true) == 0
                           ? "true" : "false");

            Console.ReadKey();
        }
    }
}



Concat(String StrX, String StrY);
/*Example: String Class Methods: InfoBrother:*/
using System;

namespace StringMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            // we want to simply quickly add this person's name together
            string fName = "Sardar";
            string mName = "Omar";
            string lName = "Pervez";

            // this line simply concatenates the two strings
            Console.WriteLine("{0} Says, Welcome to You: !", 
            string.Concat(string.Concat(fName, mName), lName));

            //To add some space between Names, we can do this:
            mName = " " + mName.Trim();
            lName = " " + lName.Trim();
            Console.WriteLine("{0} Says, Welcome to You: !",
           string.Concat(string.Concat(fName, mName), lName));

            Console.ReadKey();
        }        
    }
}

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement