Operations on Strings
Operations on Strings
Fundamental Operations on Strings
The Mutability and Immutability of a String
An object is said to be mutable if it can change at will. This means that when something, anything, such as an external action, occurs, the nature (such as structure and/or appearance) of the object changes tremendously (sometimes to abrand new object, but we are not studying biology (think of butterflies) or anthropology here). This concept is close to class inheritance where you can get a new class by deriving from an existing class and getting new functionalities from the derived class.
An object is immutable, or not mutable, if its nature cannot change. The only way to get a similar object is only to create a new object that looks, or appears, like the first one.
The string type, and therefore the String class is immutable. This means that every time you perform an operation that modifies a string object, you get a brand new string, not a copy, not a duplicate. If you manipulate many strings in your code, you may think that you should be concerned with the computer memory (as is the case in other languages such as previous versions of C++ and Pascal). Don't get concerned with memory. The C# compiler takes care of all memory concerns behind the scenes.
Practical Learning: Introducing Strings
using static System.Console; namespace PayrollPreparation3 { public class PayrollPreparation { public static void Main() { int digits = 0; int symbols = 0; int letters = 0; int numbers = 0; int lowercase = 0; int uppercase = 0; int separators = 0; int whiteSpaces = 0; int punctuations = 0; int letterOrDigits = 0; WriteLine("Account Creation"); WriteLine("---------------------------------"); WriteLine("Provide the following information"); Write("First Name: "); string strFirstName = ReadLine(); Write("Middle Name: "); string strMiddleName = ReadLine(); Write("Last Name: "); string strLastName = ReadLine(); WriteLine("---------------------------------"); Write("Password: "); string strNewPassword = ReadLine(); Write("Confirm Password: "); string strConfirmPassword = ReadLine(); Clear(); if (strNewPassword.Equals(strConfirmPassword)) { int length = strNewPassword.Length; if (strMiddleName.Length == 0) strUsername = strFirstName + strLastName; for (int i = 0; i < strNewPassword.Length - 1; i++) { if (char.IsWhiteSpace(strNewPassword, i)) whiteSpaces++; if (char.IsLetter(strNewPassword, i)) letters++; if (char.IsDigit(strNewPassword, i)) digits++; if (char.IsLetterOrDigit(strNewPassword, i)) letterOrDigits++; if (char.IsNumber(strNewPassword, i)) numbers++; if (char.IsPunctuation(strNewPassword, i)) punctuations++; if (char.IsSeparator(strNewPassword, i)) separators++; if (char.IsSymbol(strNewPassword, i)) symbols++; if (char.IsLower(strNewPassword, i)) lowercase++; if (char.IsUpper(strNewPassword, i)) uppercase++; } WriteLine("Account Summary"); WriteLine("----------------------------"); WriteLine("First Name: " + strFirstName); WriteLine("Middle Name: " + strMiddleName); WriteLine("Last Name: " + strLastName); WriteLine("-------------------------------------------"); WriteLine("Password: " + strNewPassword); WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString()); WriteLine("-------------------------------------------"); WriteLine("The password contains:"); WriteLine(" " + whiteSpaces + " white space(s)"); WriteLine(" " + symbols + " symbol(s)"); WriteLine(" " + digits + " digit(s)"); WriteLine(" " + letters + " letter(s)"); WriteLine(" " + letterOrDigits + " letter(s) or digit(s)"); WriteLine(" " + numbers + " number(s)"); WriteLine(" " + punctuations + " punctuation mark(s)"); WriteLine(" " + separators + " separator character(s)"); WriteLine(" " + lowercase + " lowercase letter(s)"); WriteLine(" " + uppercase + " uppercase letter(s)"); WriteLine("==========================================="); } else { WriteLine("The passwords you entered don't match."); } return; } }
Account Creation --------------------------------- Provide the following information First Name:
Account Creation --------------------------------- Provide the following information First Name: Roberto Middle Name: Carlos Last Name: Solorio -------------------------------- Password: $Outh0D@kota!9 Confirm Password: SouthDakota
Account Summary ------------------------------ First Name: Roberto Middle Name: Carlos Last Name: Solorio Password: $Outh0D@kota!9 ============================== Press any key to continue . . .
Adding Strings
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 static System.Console;
public class Reflections
{
static int Main()
{
string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines.\n";
string author = "President Nixon";
string quotation = quote + author;
WriteLine(quotation);
WriteLine("====================================================");
return 0;
}
}
This would produce:
Never let your head hang down. Never give up and sit down and grieve. Find anoth er way. And don't pray when it rains if you don't pray when the sun shines. President Nixon ==================================================== Press any key to continue . . .
In the same way, you can add as many strings as necessary using +. Here is an example:
using static System.Console;
public class Reflections
{
static int Main()
{
string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines.\n";
string firstName = "Richard";
string middleInitial = "M";
string lastName = "Nixon";
string quotation = quote + " - " + firstName + " " + middleInitial + ". " + lastName + " -";
WriteLine(quotation);
WriteLine("====================================================");
return 0;
}
}
This would produce:
Never let your head hang down. Never give up and sit down and grieve. Find anoth er way. And don't pray when it rains if you don't pray when the sun shines. - Richard M. Nixon - ==================================================== Press any key to continue . . .
Concatenating Some Strings
Besides the addition operator, to formally support string concatenation, the string data type 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 a group of strings and adds them.
Practical Learning: Concatenating Some Strings
using static System.Console; namespace PayrollPreparation3 { public class PayrollPreparation { public static void Main() { int digits = 0; int symbols = 0; int letters = 0; int numbers = 0; int lowercase = 0; int uppercase = 0; int separators = 0; int whiteSpaces = 0; int punctuations = 0; int letterOrDigits = 0; WriteLine("Account Creation"); WriteLine("---------------------------------"); WriteLine("Provide the following information"); Write("First Name: "); string strFirstName = ReadLine(); Write("Middle Name: "); string strMiddleName = ReadLine(); Write("Last Name: "); string strLastName = ReadLine(); WriteLine("---------------------------------"); Write("Password: "); string strNewPassword = ReadLine(); Write("Confirm Password: "); string strConfirmPassword = ReadLine(); Clear(); if (strNewPassword.Equals(strConfirmPassword)) { int length = strNewPassword.Length; string strUsername = string.Concat(strFirstName, strMiddleName, strLastName) if (strMiddleName.Length == 0) strUsername = string.Concat(strFirstName, strLastName);; for (int i = 0; i < strNewPassword.Length - 1; i++) { if (char.IsWhiteSpace(strNewPassword, i)) whiteSpaces++; if (char.IsLetter(strNewPassword, i)) letters++; if (char.IsDigit(strNewPassword, i)) digits++; if (char.IsLetterOrDigit(strNewPassword, i)) letterOrDigits++; if (char.IsNumber(strNewPassword, i)) numbers++; if (char.IsPunctuation(strNewPassword, i)) punctuations++; if (char.IsSeparator(strNewPassword, i)) separators++; if (char.IsSymbol(strNewPassword, i)) symbols++; if (char.IsLower(strNewPassword, i)) lowercase++; if (char.IsUpper(strNewPassword, i)) uppercase++; } WriteLine("Account Summary"); WriteLine("----------------------------"); WriteLine("First Name: " + strFirstName); WriteLine("Middle Name: " + strMiddleName); WriteLine("Last Name: " + strLastName); WriteLine("-------------------------------------------"); WriteLine("Username: " + strUsername); WriteLine("Password: " + strNewPassword); WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString()); WriteLine("-------------------------------------------"); WriteLine("The password contains:"); WriteLine(" " + whiteSpaces + " white space(s)"); WriteLine(" " + symbols + " symbol(s)"); WriteLine(" " + digits + " digit(s)"); WriteLine(" " + letters + " letter(s)"); WriteLine(" " + letterOrDigits + " letter(s) or digit(s)"); WriteLine(" " + numbers + " number(s)"); WriteLine(" " + punctuations + " punctuation mark(s)"); WriteLine(" " + separators + " separator character(s)"); WriteLine(" " + lowercase + " lowercase letter(s)"); WriteLine(" " + uppercase + " uppercase letter(s)"); WriteLine("==========================================="); } else { WriteLine("The passwords you entered don't match."); } return; } } }
Account Creation --------------------------------- Provide the following information First Name:
Account Creation --------------------------------- Provide the following information First Name: Stephanie Middle Name: Last Name: Crewes --------------------------------- Password: Password1 Confirm Password: Password1
Account Summary ---------------------------- First Name: Stephanie Middle Name: Last Name: Crewes ------------------------------------------- Username: StephanieCrewes Password: Password1 Password Length: 9 symbol(s)/character(s) ------------------------------------------- The password contains: 0 white space(s) 0 symbol(s) 0 digit(s) 8 letter(s) 8 letter(s) or digit(s) 0 number(s) 0 punctuation mark(s) 0 separator character(s) 7 lowercase letter(s) 1 uppercase letter(s) =========================================== Press any key to continue . . .
Compound Concatenation
To add a character or a string to an existing string, use the += operator. When the operator has been used, the string is made of the characters it previously had plus the new character(s). Here is an example:
using static System.Console;
public class Exercise
{
private static void Main()
{
string quote = "Nihilism is a natural consequence of a culture (or civilization) ruled and regulated by categories that mask manipulation, mastery and domination of peoples and nature.";
quote += " - ";
quote += "Cornel";
quote += " ";
quote += "West";
WriteLine(quote);
WriteLine("======================================");
return;
}
}
This would produce:
Nihilism is a natural consequence of a culture (or civilization) ruled and regul ated by categories that mask manipulation, mastery and domination of peoples and nature. - Cornel West ====================================== Press any key to continue . . .
Formatting a String
Formatting a string consists of specifying how it would be presented as an object. To support this operation, the string type is equipped with a static method named Format. The String.Format() method is overloaded in various versions; the syntax of the simplest version is:
public static string Format(string format, Object arg0);
This method takes two arguments. 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.
If you need two placeholders for values, use the following version of the method:
public static string Format(string format, object arg0, object arg1)
The first argument can contain a string plus {0} and {1} anywhere in the string (but {0} must come before {1}). The second argument will be used in place of {0} in the first argument, and the third argument will be used in place the {1} placeholders. Here is an example:
using System;
public class Geometry
{
static int Main()
{
double side;
Console.WriteLine("Square Processing");
try
{
Console.Write("Enter Side: ");
side = double.Parse(Console.ReadLine());
string strResult = string.Format("Square Characteristics\nSide: {0}\nPerimeter: {0}", side, side * 4);
Console.WriteLine(strResult);
}
catch (FormatException)
{
Console.WriteLine("You typed an invalid number");
}
return 0;
}
}
If you need three placeholders for values, use the following version of the method:
public static string Format(string format, object arg0, object arg1, object arg2)
The first argument can contain a string plus {0}, {1}, and {2} anywhere in the string (but the {0}, {1}, and {2} must appear in that order). The second argument will be used in place of {0} in the first argument, the third argument will be used in place the {1} placeholder, and the fourth argument will be used in place of {2}.
If you need more than three placeholders for values, use the following version of the method:
public static string Format(string format, params object[] args)
The first argument can contain one or a combination of {number} placeholders. The second argument is one or a combination of values that would be orderly added to the {number} placeholders of the first argument.
String Interpolation
String interpolation consists of starting string formatting with the $ symbol followed by the normal double-quotes where the string contains one or a combination of {}. Between the curly brackets, type the name of the variable whose values would be displayed. Here are examples:
using static System.Console;
namespace PayrollPreparation
{
public class PayrollPreparation
{
public static void Main()
{
WriteLine("Account Creation");
WriteLine("---------------------------------");
WriteLine("Provide the following information");
Write("First Name: ");
string strFirstName = ReadLine();
Write("Middle Name: ");
string strMiddleName = ReadLine();
Write("Last Name: ");
string strLastName = ReadLine();
string strResult = $"{strFirstName} {strMiddleName} {strLastName}";
Clear();
WriteLine("Account Summary");
WriteLine("---------------------------------");
WriteLine("Full Name: {0}", strResult);
WriteLine("=================================");
return;
}
}
}
Here is a test:
Account Creation --------------------------------- Provide the following information First Name: Andrea Middle Name: Melodie Last Name: Rhodes
This would produce:
Account Summary --------------------------------- Full Name: Andrea Melodie Rhodes ================================= Press any key to continue . . .
You an also pass a string interpolation to the Console.Write() or the Console.WriteLine() method. Here are examples:
using static System.Console; public class PayrollPreparation { public static void Main() { int digits = 0; int symbols = 0; int letters = 0; int numbers = 0; int lowercase = 0; int uppercase = 0; int separators = 0; int whiteSpaces = 0; int punctuations = 0; int letterOrDigits = 0; WriteLine("Account Creation"); WriteLine("---------------------------------"); WriteLine("Provide the following information"); Write("First Name: "); string strFirstName = ReadLine(); Write("Middle Name: "); string strMiddleName = ReadLine(); Write("Last Name: "); string strLastName = ReadLine(); WriteLine("---------------------------------"); Write("Password: "); string strNewPassword = ReadLine(); Write("Confirm Password: "); string strConfirmPassword = ReadLine(); Clear(); if (strNewPassword.Equals(strConfirmPassword)) { int length = strNewPassword.Length; for (int i = 0; i < strNewPassword.Length - 1; i++) { if (char.IsWhiteSpace(strNewPassword, i)) whiteSpaces++; if (char.IsLetter(strNewPassword, i)) letters++; if (char.IsDigit(strNewPassword, i)) digits++; if (char.IsLetterOrDigit(strNewPassword, i)) letterOrDigits++; if (char.IsNumber(strNewPassword, i)) numbers++; if (char.IsPunctuation(strNewPassword, i)) punctuations++; if (char.IsSeparator(strNewPassword, i)) separators++; if (char.IsSymbol(strNewPassword, i)) symbols++; if (char.IsLower(strNewPassword, i)) lowercase++; if (char.IsUpper(strNewPassword, i)) uppercase++; } string fullName = $"{strFirstName} {strMiddleName} {strLastName}"; WriteLine("Account Summary"); WriteLine("----------------------------"); WriteLine($"Full Name: {fullName}"); WriteLine("-------------------------------------------"); WriteLine($"Password: {strNewPassword}"); WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString()); WriteLine("-------------------------------------------"); WriteLine("The password contains:"); WriteLine($" {whiteSpaces} white space(s)"); WriteLine($" {symbols} symbol(s)"); WriteLine($" {digits} digit(s)"); WriteLine($" {letters} letter(s)"); WriteLine($" {letterOrDigits} letter(s) or digit(s)"); WriteLine($" {numbers} number(s)"); WriteLine($" {punctuations} punctuation mark(s)"); WriteLine($" {separators} separator character(s)"); WriteLine($" {lowercase} lowercase letter(s)"); WriteLine($" {uppercase} uppercase letter(s)"); WriteLine("==========================================="); } else { WriteLine("The passwords you entered don't match."); } return; } }
Sub-Strings
Introduction
A sub-string is a section or part of a string. Obviously, to get a sub-string, you first need an existing string.
Fundamentals of Creating a Sub-String
There are various ways you can create a sub-string from an existing string. As one way, you can retrieve one or more characters from an existing string. To support this, the string class is equipped with a method named Substring() that is overloaded with 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.
Another technique to create a sub-string consists of extracting it from the beginning of an 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.
Practical Learning: Creating Sub-Strings
using static System.Console; namespace PayrollPreparation3 { public class PayrollPreparation { public static void Main() { int digits = 0; int symbols = 0; int letters = 0; int numbers = 0; int lowercase = 0; int uppercase = 0; int separators = 0; int whiteSpaces = 0; int punctuations = 0; int letterOrDigits = 0; WriteLine("Account Creation"); WriteLine("---------------------------------"); WriteLine("Provide the following information"); Write("First Name: "); string strFirstName = ReadLine(); Write("Middle Name: "); string strMiddleName = ReadLine(); Write("Last Name: "); string strLastName = ReadLine(); WriteLine("---------------------------------"); Write("Password: "); string strNewPassword = ReadLine(); Write("Confirm Password: "); string strConfirmPassword = ReadLine(); Clear(); if (strNewPassword.Equals(strConfirmPassword)) { string strUsername = string.Empty; int length = strNewPassword.Length; if (strMiddleName.Length == 0) strUsername = string.Concat(strFirstName.Substring(0, 1), strLastName).ToLower(); else strUsername = string.Concat(strFirstName.Substring(0, 1), strMiddleName.Substring(0, 1), strLastName).ToLower(); for (int i = 0; i < strNewPassword.Length - 1; i++) { if (char.IsWhiteSpace(strNewPassword, i)) whiteSpaces++; if (char.IsLetter(strNewPassword, i)) letters++; if (char.IsDigit(strNewPassword, i)) digits++; if (char.IsLetterOrDigit(strNewPassword, i)) letterOrDigits++; if (char.IsNumber(strNewPassword, i)) numbers++; if (char.IsPunctuation(strNewPassword, i)) punctuations++; if (char.IsSeparator(strNewPassword, i)) separators++; if (char.IsSymbol(strNewPassword, i)) symbols++; if (char.IsLower(strNewPassword, i)) lowercase++; if (char.IsUpper(strNewPassword, i)) uppercase++; } WriteLine("Account Summary"); WriteLine("----------------------------"); WriteLine("First Name: " + strFirstName); WriteLine("Middle Name: " + strMiddleName); WriteLine("Last Name: " + strLastName); WriteLine("-------------------------------------------"); WriteLine("Username: " + strUsername); WriteLine("Password: " + strNewPassword); WriteLine("Password Length: {0} symbol(s)/character(s)", length.ToString()); WriteLine("-------------------------------------------"); WriteLine("The password contains:"); WriteLine(" " + whiteSpaces + " white space(s)"); WriteLine(" " + symbols + " symbol(s)"); WriteLine(" " + digits + " digit(s)"); WriteLine(" " + letters + " letter(s)"); WriteLine(" " + letterOrDigits + " letter(s) or digit(s)"); WriteLine(" " + numbers + " number(s)"); WriteLine(" " + punctuations + " punctuation mark(s)"); WriteLine(" " + separators + " separator character(s)"); WriteLine(" " + lowercase + " lowercase letter(s)"); WriteLine(" " + uppercase + " uppercase letter(s)"); WriteLine("==========================================="); } else { WriteLine("The passwords you entered don't match."); } return; } } }
Account Creation --------------------------------- Provide the following information First Name:
Account Creation --------------------------------- Provide the following information First Name: Roberto Middle Name: Carlos Last Name: Solorio --------------------------------- Password: P@s$w0rd #2000 Confirm Password: P@s$w0rd #2000
Account Summary ---------------------------- First Name: Roberto Middle Name: Carlos Last Name: Solorio ------------------------------------------- Username: rcsolorio Password: P@s$w0rd #2000 Password Length: 14 symbol(s)/character(s) ------------------------------------------- The password contains: 1 white space(s) 1 symbol(s) 4 digit(s) 5 letter(s) 9 letter(s) or digit(s) 4 number(s) 2 punctuation mark(s) 1 separator character(s) 4 lowercase letter(s) 1 uppercase letter(s) =========================================== Press any key to continue . . .
Account Creation --------------------------------- Provide the following information First Name: Stephanie Middle Name: Last Name: Crewes --------------------------------- Password: $Up3R Pr1v8te W0rld4? Confirm Password: $Up3R Pr1v8te W0rld4?
Account Summary ---------------------------- First Name: Stephanie Middle Name: Last Name: Crewes ------------------------------------------- Username: screwes Password: $Up3R Pr1v8te W0rld4? Password Length: 21 symbol(s)/character(s) ------------------------------------------- The password contains: 2 white space(s) 1 symbol(s) 5 digit(s) 12 letter(s) 17 letter(s) or digit(s) 5 number(s) 0 punctuation mark(s) 2 separator character(s) 8 lowercase letter(s) 4 uppercase letter(s) =========================================== Press any key to continue . . .
Looking for a Character or a Sub-String in a String
To assist you with looking for a character or a sub-string within a string, the String class provides a method named Contains. Its syntax is:
public bool Contains(string value)
Unwanted Characters and Sections in a String
Trimming a String
Trimming a string consists of removing empty spaces from it. To let you remove empty spaces from the left side of a string, the String class is equipped with a method named TrimStart. Its syntax is:
public string TrimStart(params char[] trimChars)
To let you remove empty spaces from the right side of a string, the String class provides the TrimEnd method. Its syntax is:
public string TrimEnd(params char[] trimChars)
To let you remove empty spaces from both sides of a string, the String class is equipped with a method named Trim. It is overloaded with two versions. Their syntaxes are:
public string Trim() public string Trim(params char[] trimChars)
Replacing a Character
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 a method named Replace 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.
Replacing a Sub-String
Inside of a string, if you have a combination of consecutive characters you don't want to keep, you can either remove that sub-string or replace it with a new combination of consecutive characters of your choice. To support this operation, the String class provides a version of 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.
Duplicating a String
Copying a String
After declaring and initializing one String variable, you can assign it to another String variable using the assignment operator. Here is an example:
string strPerson = "Charles Stanley";
string strSomebody = strPerson;
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:
string strPerson = "Charles Stanley";
string strSomebody = string.Copy(strPerson);
Copying To a String
The string.Copy() method is used to copy all characters of one string into another another. To let you copy only a few characters, the String class is equipped with a method named CopyTo. Its syntax is:
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
Strings and classes
Passing a String to a Function or Method
Like a normal value, a string can be passed to a method. When calling the method, you can pass a value for the argument in double-quotes or provide the name of a variable that holds the string.
Returning a String From a Method
You can create a method that returns a string. This is done the same way as with the other classes.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|