To declare a variable that can hold one character, a letter, or a symbol, user the char data type or the var keyword if you are also initializing the variable. To initialize the variable, include its value between two single-quotes. Here are examples: using System; public static class Exercise { public static int Main(string[] args) { var gender = 'm'; var moneySymbol = '$'; var multiplication = '*'; var numberOne = '1'; Console.WriteLine("A few characters"); Console.WriteLine("Gender: {0}", gender); Console.WriteLine("Money Symbol: {0}", moneySymbol); Console.WriteLine("Multiplication: {0}", multiplication); Console.WriteLine("Number One: {0}", numberOne); return 0; } } This would produce: A few characters Gender: m Money Symbol: $ Multiplication: * Number One: 1 Press any key to continue...
In different programs so far, when we needed a string object, we would declare a variable of type string. To support strings, the .NET Framework provides the String class. This class is defined in the C# language as the string data type. Here is an example of declaring, initializing, and using a string object: using System; public class Exercise { static int Main(string[] args) { var gender = "Female"; Console.WriteLine("Gender: {0}\n", gender); return 0; } } This would produce: Gender: Female Press any key to continue . . . From what we have studied about arrays, if you observe a value such as "Female", you may see that it primarily resembles a collection of characters. A string is a group of characters. This also means that a string is an array of characters. After declaring and initializing a string, it is considered an array of values where each character occupies a specific position. The positioned are numbered so that the most left character of the string occupies index 0; the second character is at index 1, and so on. To support this idea of an array of characters, the String class is equipped with an indexed property named Chars. This is also how you can retrieve the character at a specific index in the string, using the [] operator of arrays. Here is an example: using System; public class Exercise { static int Main(string[] args) { var gender = "Female"; var gdr = gender[2]; Console.WriteLine("Gender: {0}", gender); Console.WriteLine("Character: {0}", gdr); Console.WriteLine(); return 0; } } This would produce: Gender: Female Character: m Press any key to continue . . . Once (and because) a string is considered a collection of items, you can use the foreach operator to access each member of the collection. Here is an example: using System; class Exercise { static int Main(string[] args) { var gender = "Female"; Console.WriteLine("Gender: {0}", gender); Console.WriteLine("\nIndividual Characters"); foreach(char c in gender) Console.WriteLine("Character: {0}", c); return 0; } } This would produce: Gender: Female Individual Characters Character: F Character: e Character: m Character: a Character: l Character: e Press any key to continue . . . The English language uses two character representations: lowercase and uppercase. The characters in lowercase are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. The equivalent characters in uppercase are represented as A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Characters used for counting are called numeric characters; each one of them is called a digit. They are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. There are other characters used to represent things in computer applications, mathematics, and others. Some of these characters, also called symbols are ~ , ! @ # $ % ^ & * ( ) _ + { } ` | = [ ] \ : " ; ' < > ? , . / These characters are used for various reasons and under different circumstances. For example, some of them are used as operators in mathematics or in computer programming. Regardless of whether a character is easily identifiable or not, all these symbols are character types and can be declared using the char data type followed by a name. An alphabetic character, for any reason judged necessary, can be converted from one case to another. The other characters, non-alphabetic symbols, and the numbers, do not have a case and therefore cannot be converted in cases. To convert a string from lowercase to uppercase, you can call use the ToUpper() method of the String class. It is overloaded with two versions. One of the versions of this method uses the following syntax: public string ToUpper(); This method takes no argument. This method considers each character of the string that called it. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept “as-isâ€ÂÂ. Here is an example: using System; public class Program { static int Main(string[] args) { var strFullName = "Alexander Patrick Katts"; var strConversion = strFullName.ToUpper(); Console.WriteLine("Full Name: " + strFullName); Console.WriteLine("Full Name: " + strConversion); return 0; } } This would produce: Full Name: Alexander Patrick Katts Full Name: ALEXANDER PATRICK KATTS Press any key to continue . . . To convert a string to lowercase, you can call the String.ToLower() method. Its syntax is: public string ToLower(); This method follows the same logic as its counterpart: it scans the string that called it, visiting each character. If the character is not an alphabetic character, it would be kept “as-isâ€ÂÂ. If the character is an uppercase alphabetic character, it would be converted to lowercase. If it is in lowercase, it would not be converted.
If you have a string that contains a wrong character, you can either delete that character or replace it with another character of your choice. To support this operation, the String class is equipped with the Replace() method that is overloaded with two versions. One of the versions of the String.Replace() method uses the following syntax: public string Replace(char oldChar, char newChar); The first argument of this method is used to identify the sought character. If and everywhere that character is found in the string, it would be replaced by the character passed as the second argument. Here is an example that received a telephone number from the user and it stripped that phone number with various things to end up with only the digits: using System; public class Program { static int Main() { var PhoneNumber = ""; Console.Write("Enter Phone Number: "); PhoneNumber = Console.ReadLine(); // Get a telephone number from the user Console.Write("\nPhone Number: "); Console.WriteLine(PhoneNumber); // Remove the spaces PhoneNumber = PhoneNumber.Replace(" ", ""); Console.Write("\nPhone Number: "); Console.WriteLine(PhoneNumber); // Remove the left parenthesis, if any PhoneNumber = PhoneNumber.Replace("(", ""); // Remove the right parenthesis, if any PhoneNumber = PhoneNumber.Replace(")", ""); // Remove the dash, if any PhoneNumber = PhoneNumber.Replace("-", ""); Console.Write("\nPhone Number: "); Console.Write(PhoneNumber); return 0; } } Here is an example of running the program: Enter Phone Number: (303) 826-4603 Phone Number: (303) 826-4603 Phone Number: (303)826-4603 Phone Number: 3038264603 Press any key to continue . . .
In many operations, you will need to know the number of characters a string consists of. To get the size of a string, The String class provides the Length member variable. Here is an example of using it: using System; public class Exercise { static int Main(string[] args) { var gender = "Female"; Console.WriteLine("Gender: {0}", gender); Console.WriteLine("Length: {0} Characters\n", gender.Length); return 0; } } This would produce: Gender: Female Length: 6 Characters Press any key to continue . . . In the same way, you can access the Length property when processing the individual characters of a string. Here is an example: using System; public class Exercise { static int Main(string[] args) { var gender = "Female"; Console.WriteLine("Gender: {0}", gender); Console.WriteLine("Length: {0} Characters", gender.Length); Console.WriteLine("\nIndividual Characters"); for (int c = 0; c < gender.Length; c++) Console.WriteLine("Index[{0}]: {1}", c, gender[c]); return 0; } } This would produce: Gender: Female Length: 6 Characters Individual Characters Index[0]: F Index[1]: e Index[2]: m Index[3]: a Index[4]: l Index[5]: e Press any key to continue . . .
One of the routine operations you can perform on two strings consists of adding one to another, that is, putting one string to the right of another string, to produce a new string made of both. There are two techniques you can use. To add one string to another, you can use the addition operator as done in arithmetic. Here is an example: using System; public class Exercise { static int Main(string[] args) { var strNeed = "Needs"; var strRepair = "Repair"; var strAddition = strNeed + strRepair; Console.WriteLine(strAddition); return 0; } } This would produce: NeedsRepair Press any key to continue . . . In the same way, you can add as many strings as necessary using +. Here is an example: using System; public class Exercise { static int Main(string[] args) { var strfirstName = "Alexander"; var strMiddleName = "Patrick"; var strlastName = "Katts"; var strFullName = strfirstName + " " + strMiddleName + " " + strlastName; Console.WriteLine("First Name: " + strfirstName); Console.WriteLine("Middle Name: " + strMiddleName); Console.WriteLine("Last Name: " + strlastName); Console.WriteLine("Full Name: " + strFullName + "\n"); return 0; } } This would produce: First Name: Alexander Middle Name: Patrick Last Name: Katts Full Name: Alexander Patrick Katts Press any key to continue . . . Besides the addition operator, to formally support string concatenation, the String class provides the Concat() method that is overloaded in various versions. One of the versions of this method takes two String arguments. Its syntax is: public static string Concat(string str1, string str2); This versions takes two strings that should be concatenated. The method returns a new string as the first added to the second. Two imitations of this version use the following versions: public static string Concat(string str0, string str1, string str2); public static string Concat(string str0, string str1, string str2, string str3); In each case, the method takes the number of strings and adds them.
Inside of a string, if you have a combination of consecutive character you don't want to keep, you can either remove that sub-string or replace it with an new combination of consecutive characters of your choice. To support this operation, the String class provides anopther version of the the Replace() method whose syntax is: public string Replace(string oldStr, string newStr); The oldStr argument is the sub-string to look for in the string. Whenever that sub-string is found in the string, it is replaced by the newStr argument.
Formatting a string consists of specifying how it would be presented as an object. To support this operation, the String class is equipped with a static method named Format. The String.Format() method is overloaded in various versions; the syntax of the simplest is: public static string Format(string format, Object arg0); This method takes two arguments and it follows the same techniques we reviewed in Lesson 5 for data formatting. This means that the first argument can contain one or a combination of {} operators that include incrementing numbers. The second argument contains one or a combination of values that would be added to the {} operators of the first argument. Here is an example: using System; public class Exercise { static int Main(string[] args) { var wage = 22.45; var strDisplay = string.Format("Hourly Salary: {0}", wage); Console.WriteLine(strDisplay); return 0; } } This would produce: Side: 25.85 Hourly Salary: 22.45 Press any key to continue . . .
After declaring and initializing one String variable, you can assign it to another String variable using the assignment operator. Here is an example: using System; public class Exercise { static int Main() { var strPerson = "Charles Stanley"; var strSomebody = strPerson; Console.WriteLine("Full Name: " + strPerson); Console.WriteLine("Full Name: " + strSomebody); return 0; } } This would produce: Full Name: Charles Stanley Full Name: Charles Stanley Press any key to continue . . . Assigning one variable to another is referred to as copying it. To formally support this operator, the String class is equipped with the Copy() method. Its syntax is: public static string Copy(string str); This method takes as argument an existing String object and copies it, producing a new string. Here is an example: using System; class Program { static int Main(string[] args) { var strPerson = "Charles Stanley"; var strSomebody = string.Copy(strPerson); Console.WriteLine("Full Name: " + strPerson); Console.WriteLine("Full Name: " + strSomebody); return 0; } } The string.Copy() method is used to copy all characters of one string into another another. If you want to copy only a few characters, use the string.CopyTo() method. Its syntax is: public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
String comparison consists of examining the characters of two strings with a character of one string compared to a character of the other string with both characters at the same positions. To support this operation, the string class is equipped with the Compare() method that is overloaded in many versions. One of the versions uses the following syntax: public static int Compare(string String1, string String2); This method is declared static and it takes two arguments. When it starts, the first character of the first argument is compared to the first character of the second string. Alphabetically, if the first character of the first string has a lower alphabetical index than the first character of the second, this method returns a negative value. If the first character of the first string has a higher alphabetical index than the first character of the second, this method returns a positive value. If the first characters of both strings are the same, the method continues with the second character of each string. If both strings have the exact same characters, the method returns 0. This can be resumed as follows. The method returns
Here is an example: using System; public class Exercise { static int Main(string[] args) { var firstName1 = "Andy"; var lastName1 = "Stanley"; var firstName2 = "Charles"; var lastName2 = "Stanley"; var Value1 = string.Compare(firstName1, firstName2); var Value2 = string.Compare(firstName2, firstName1); var Value3 = string.Compare(lastName1, lastName2); Console.WriteLine("The result of comparing " + firstName1 + " and " + firstName2 + " is\t" + Value1.ToString()); Console.WriteLine("The result of comparing " + firstName2 + " and " + firstName1 + " is\t" + Value2.ToString()); Console.WriteLine("The result of comparing " + lastName1 + " and " + lastName2 + " is\t" + Value3.ToString() + "\n"); return 0; } } This would produce: The result of comparing Andy and Charles is -1 The result of comparing Charles and Andy is 1 The result of comparing Stanley and Stanley is 0 Press any key to continue... When using this version of the string.Compare() method, the case (upper or lower) of each character is considered. If you don't want to consider this factor, the String class proposes another version of the method. Its syntax is: public static int Compare(string String1, string String2, bool ignoreCase); The third argument allows you to ignore the case of the characters when performing the comparison.
In the previous section, we saw that the indexed-equivalent characters of two strings can be compared to know whether one is lower or higher than the other's. If you are only interested to know whether two strings are equivalent, you can call the Equals() method of the string class. It is overloaded with various versions. Two versions use the following syntaxes: public override bool Equals(object obj); public bool Equals(string value); When calling one of these versions, use an object object or a string variable that calls it. The method takes one argument. The variable that calls the method is compared to the value passed as argument. If both values are the exact same, the method returns true. The comparison is performed considering the case of each character. If you don't want to consider the case, use the following version of the method: public bool Equals(string value, StringComparison comparisonType); An alternative to the second syntax is to use a static version of this method whose syntax is: public static bool Equals(string a, string b); This method takes two string arguments and compares them. If they are the same, the method returns true. This method considers the cases of the characters. If you don't want this factor taken into consideration, use the following version of the method: public static bool Equals(string a, string b, StringComparison comparisonType);
A sub-string is a section or part of a string. To create a sub-string, you first need a string and can retrieve one or more values from it. To support this, the string class is equipped with the Substring() method that is overloaded in two versions. The syntax of one is: public string Substring(int startIndex); The integer argument specifies the position of the first character from the variable that called the method. The return value is a new String that is made of the characters from startIndex to the end of the string.
Probably the most consistent way to create a string is to control the beginning and end retrieved from the original string. To support this, the string class is equipped with another version of the Substring() method. Its syntax is: public string Substring(int startIndex, int length); The first argument specifies the index of the character to start from the String variable that calls this method. The second argument specifies the length of the string.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||