Understanding Boolean Logic


Boolean logic is a special type of arithmetic/comparison. Boolean logic is used to evaluate expressions to either True or False. This might be a new concept to you, but don't worryit's not difficult to understand. Boolean logic is performed using a logical operator. Consider the following sentence:

If black is a color and wood comes from trees then print "ice cream".

At first glance, it might seem that this is nonsensical. However, Visual C# could make sense of this statement using Boolean logic. First, notice that three expressions are actually being evaluated within this single sentence. I've added parentheses in the following sentence to clarify the two most obvious expressions.

If (black is a color) and (wood comes from trees) then print "ice cream".

Boolean logic evaluates every expression to either True or False. Therefore, substituting True or False for each of these expressions yields the following:

If (True) and (True) then print "ice cream".

Now, for the sake of clarity, here's the same sentence with parentheses placed around the final expression to be evaluated:

If (True And True) then print "ice cream".

This is the point where the logical operators come into play. The And (&) operator returns true if the expressions on each side of the And (&) operator are true (see Table 12.2 for a complete list of logical operators). In the sentence we're considering, the expressions on both sides of the And (&) operator are TRue, so the expression evaluates to true. Replacing the expression with TRue yields:

If True then print "ice cream".

Table 12.2. Logical (Boolean) Operators

Operator

Description

And (&&)

Evaluates to TRue when the expressions on both sides are TRue.

Not (!)

Evaluates to TRue when its expression evaluates to false;otherwise, it returns false (the true/false value of the expression is negated, or reversed).

Or (||)

Evaluates to true if an expression on either side evaluates to true.

Xor (^)

Evaluates to true if one, and only one, expression on either side evaluates to TRue.


This would result in the word "ice cream" being printed. If the expression had evaluated to False, nothing would print. As you'll see in Hour 13, the decision constructs always evaluate their expressions to either True or False, executing statements according to the results.

Using the And (&) Operator

The And (&) operator is used to perform a logical conjunction. If the expressions on both sides of the And (&) operator evaluate to true, the And (&) operation evaluates to true. If either expression is false, the And (&) operation evaluates to false, as illustrated in the following examples:

Debug.WriteLine(true & true);            // Prints true Debug.WriteLine(true & false);           // Prints false Debug.WriteLine(false & true);           // Prints false Debug.WriteLine(false & false);          // Prints false Debug.WriteLine((32 > 4) & (6 == 6));    // Prints true


Using the Not (!) Operator

The Not(!) operator performs a logical negation. That is, it returns the opposite of the expression. Consider the following examples:

Debug.WriteLine(! (true));     // Prints false Debug.WriteLine(! (false));    // Prints true Debug.WriteLine(! (5 == 5));   // Prints false Debug.WriteLine(!(4 < 2));     // Prints true


The first two statements are easy enough; the opposite of TRue is false and vice versa. For the third statement, remember that Visual C#'s operator precedence dictates that arithmetic operators are evaluated first (even if no parentheses are used), so the first step of the evaluation would look like this:

Debug.WriteLine(! (true));


The opposite of true is false, of course, so Visual C# prints false.

The fourth statement would evaluate to

Debug.WriteLine(!(false));


This happens because 4 is not less than 2, which is the expression Visual C# .NET evaluates first. Because the opposite of false is true, this statement would print true.

Using the Or (|) Operator

The Or (|) operator is used to perform a logical disjunction. If the expression to the left or right of the Or (|) operator evaluates to true, the Or (|) operation evaluates to TRue. The following are examples using Or (|) operations, and their results:

Debug.WriteLine(true | true);            // Prints true Debug.WriteLine(true | false);           // Prints true Debug.WriteLine(false | true);           // Prints true Debug.WriteLine(false | false);          // Prints false Debug.WriteLine((32 < 4) | (6 == 6));    // Prints true


Using the Xor (^) Operator

The Xor (^) operator performs a nifty little function. I personally haven't had to use it much, but it's great for those times when its functionality is required. If oneand only oneof the expressions on either side of the Xor (^) operator is true, the Xor (^) operation evaluates to TRue. Take a close look at the following statement examples to see how this works:

Debug.WriteLine(true ^ true);           // Prints false Debug.WriteLine(true ^ false);          // Prints true Debug.WriteLine(false ^ true);          // Prints true Debug.WriteLine(false ^ false);         // Prints false Debug.WriteLine((32 < 4) ^ (6 == 6));   // Prints true


Manipulating Strings

Recall from Hour 11 that a string is text. Visual C# provides many functions for working with strings. Although string manipulation isn't technically arithmetic, the things that you do with strings are similar to things you do with numbers, such as adding two strings together; string manipulation is much like creating equations. Chances are you'll be working with strings a lot in your applications. Visual C# includes a number of functions that enable you to do things with strings, such as retrieve a portion of string or find one string within another. In the following sections, you'll learn the basics of string manipulation.

Concatenating Strings of Text

Visual C# makes it possible to "add" two strings of text together to form one string. Although purists will say it's not truly a form of arithmetic, it's very much like performing arithmetic on strings, so this hour is the logical place in which to present this material. The process of adding two strings together is called concatenation. Concatenation is very common. For example, you may want to concatenate variables with hard-coded strings to display meaningful messages to the user, such as Are you sure you want to delete the user XXX?, where XXX is the contents of a variable.

To concatenate two strings, you use the + operator as shown in this line of code:

Debug.WriteLine("This is" + "a test.");


This statement would print:

This isa test.


Notice that there is no space between the words is and a. You could easily add a space by including one after the word is in the first string or before the a in the second string, or you could concatenate the space as a separate string, like this:

Debug.WriteLine("This is" + " " + "a test.");


Text placed directly within quotes is called a literal. Variables are concatenated in the same way as literals and can even be concatenated with literals. The following code creates two variables, sets the value of the first variable to "Mike," and sets the value of the second variable to the result of concatenating the variable with a space and the literal "Saklar":

string strFullName; string strFirstName = "Mike"; strFullName = strFirstName + " " + "Saklar";


The final result is that the variable strFullName contains the string Mike Saklar. Get comfortable with concatenating strings of textyou'll do this often.

Using the Basic String Methods and Properties

Visual C# includes a number of functions that make working with strings of text considerably easier than it might be otherwise. These functions enable you to easily retrieve a piece of text from a string, compute the number of characters in a string, and even determine whether one string contains another. The following is a summary of the basic string functions.

Determining the Number of Characters Using Length

The Length property of the string object returns the variable's length. The following statement prints 26, the total number of characters in the literal string "Pink Floyd reigns supreme." Remember, the quotes surrounding the string tell Visual C# .NET that the text within them is a literal; they are not part of the string.

Debug.WriteLine(("Pink Floyd reigns supreme.").Length);    // Prints 26


Retrieving Text from a String Using the Substring() Method

The Substring() method retrieves a part of a string and can be used with the following parameters:

public string Substring(startposition, numberofcharacters);


For example, the following statement prints Queen, the first five characters of the string:

Debug.WriteLine(("Queen to Queen's Level Three.").Substring(0,5));


The arguments used in this Substring() example are 0 and 5. The 0 indicates starting at the 0 position of the string (beginning). The 5 indicates the specified length to return (characters to retrieve).

The Substring() method is commonly used with the IndexOf() method (discussed shortly) to retrieve the path portion of a variable containing a filename and path combination, such as c:\Myfile.txt. If you know where the \ character is, you can use Substring() to get the path.

By the Way

If the number of characters requested is greater than the number of characters in the string, an exception (error) occurs. If you're unsure about the number of characters in the string, use the Length property of the string to find out. (Exception handling is reviewed in Hour 15.)


Determining Whether One String Contains Another Using IndexOf() Method

At times you'll need to determine whether one string exists within another. For example, suppose you let users enter their full names into a text box, and you want to separate the first and last names before saving them into individual fields in a database. The easiest way to do this is to look for the space in the string that separates the first name from the last. You could use a loop to examine each character in the string until you find the space, but Visual C# includes a string method that does this for you, faster and easier than you could do it yourself: the IndexOf() method. The basic IndexOf() method has the following syntax:

MyString.IndexOf(searchstring);


The IndexOf() method of a string searches the string for the occurrence of a string passed as an argument. If the string is found, the location of the start of the string is returned (with 0 being the first character, 1 being the second, etc.). If the search string is not found within the other string, -1 is returned. The IndexOf() method can be used with the following arguments (actually, there are additional ways and these are listed in the online help text):

  • public int IndexOf(searchstring);

  • public int IndexOf(searchstring, startinglocation);

  • public int IndexOf(searchstring, startinglocation, numberofcharacterstosearch);

The following code searches a variable containing the text "Monte Sothman", locates the space, and uses the Substring() method and Length property to place the first and last names in separate variables.

string strFullName = "Monte Sothman"; string strFirstName, strLastName; int intLocation, intLength; intLength = strFullName.Length; intLocation = strFullName.IndexOf(" "); strFirstName = strFullName.Substring(0, intLocation); strLastName = strFullName.Substring(intLocation + 1);


Did you Know?

This code assumes that a space will be found and that it won't be the first or last character in the string. In your applications, your code may need to be more robust, including checking to ensure that IndexOf() returned a value other than -1, which would indicate that no space was found.


When this code runs, IndexOf() returns 5, the ordinal position of the first space found (remember, 0 is the first character, not 1). Notice how I subtracted an additional character when using SubString() to initialize the strLastName variable; this was to take the space into account.

Trimming Beginning and Trailing Spaces from a String

As you work with strings, you'll often encounter situations in which spaces exist at the beginning or ending of strings. The .NET Framework includes the following four methods for automatically removing spaces from the beginning or end of a string:

Method

Description

String.Trim()

Removes spaces from the beginning and end of a string

String.TrimEnd()

Removes spaces from the end of a string

String.TrimStart()

Removes spaces from the beginning of a string

String.Remove ()

Removes a specified number of characters from a specified index position in a string


Replacing Text Within a String

It's not uncommon to have to replace a piece of text within a string with some other text. For example, some people still put two spaces at the end of a sentence, even though this is no longer necessary because of proportional fonts. You could replace all double-spaces with a single space using a loop and the string manipulation functions discussed so far, but there is an easier way: the Replace() method of the String class. A basic Replace() method call has the following syntax:

Stringobject.Replace(findtext, replacetext);


The findtext argument is used to specify the text to look for within expression, and the replacetext argument is used to specify the text used to replace the findtext. Consider the following code:

string strText = "Give a man a fish"; strText = strText.Replace("fish", "sandwich");


When this code completes, strText contains the string 'Give a man a sandwich'. Replace is a powerful function that can save many lines of code, and you should use it in place of a "home-grown" replace function whenever possible.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net