/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;
// Declare a delegate.
delegate void strMod(ref string str);
public class StringOps {
// Replaces spaces with hyphens.
static void replaceSpaces(ref string a) {
Console.WriteLine("Replaces spaces with hyphens.");
a = a.Replace(' ', '-');
}
// Remove spaces.
static void removeSpaces(ref string a) {
string temp = "";
int i;
Console.WriteLine("Removing spaces.");
for(i=0; i < a.Length; i++)
if(a[i] != ' ') temp += a[i];
a = temp;
}
// Reverse a string.
static void reverse(ref string a) {
string temp = "";
int i, j;
Console.WriteLine("Reversing string.");
for(j=0, i=a.Length-1; i >= 0; i--, j++)
temp += a[i];
a = temp;
}
public static void Main() {
// Construct delegates.
strMod strOp;
strMod replaceSp = new strMod(replaceSpaces);
strMod removeSp = new strMod(removeSpaces);
strMod reverseStr = new strMod(reverse);
string str = "This is a test";
// Set up multicast.
strOp = replaceSp;
strOp += reverseStr;
// Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
// Remove replace and add remove.
strOp -= replaceSp;
strOp += removeSp;
str = "This is a test."; // reset string
// Call multicast.
strOp(ref str);
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
}
}
|