Tutorial #7: Source Code Listings
Demonstrates use of the Length property of the string class
using System;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
string name = "";
do {
Console.Write("Please enter a name (enter \"quit\" to exit program): ");
name = Console.ReadLine();
if (name.Trim().ToLower() != "quit") {
Console.WriteLine("\"{0}\", is {1} characters in length.\n", name, name.Length);
}
} while (name.Trim().ToLower() != "quit");
}
}
}
Demonstrates using special escape characters to produce unusual sybmols
using System;
class Program{
static void Main(){
Console.Write("This is Omega: {0}. And this is Sigma: {1} ",
"\u03A9", "\u03A3");
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates that a string assigned a null value will throw an exception if you attempt to use its Length property
using System;
class Program{
static void Main(){
string mystring = null;
Console.WriteLine("Length of mystring is {0}", mystring.Length);
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates the overloaded String constructor of the form String(char, int)
using System;
class Program{
static void Main(){
Console.WriteLine();
string s = new string('a',5);
Console.WriteLine(s);
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates taking the first character from multiple user-entries, then concatenating them into a string. Makes use of the Indexer of the string variable named entry.
using System;
class Program{
static void Main(){
string entry = string.Empty;
string mystring = string.Empty;
Console.WriteLine();
do{
Console.Write("Enter a single keyboard character (a \"q\" indicates you're finished): ");
entry = Console.ReadLine().Trim().ToLower();
if(entry!="quit"){
// char[] chararray = entry.ToCharArray();
mystring += entry[0];
}
}while(entry!="quit");
Console.WriteLine("\nThe string concatenated from your entries is: \"{0}\"", mystring);
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates using an overloaded string constructor to form a string from a character array.
using System;
class Program{
static void Main(){
char[] mychararray = new char[5]{'B','r','y','a','n'};
string mystring = new string(mychararray);
Console.WriteLine("\nThe 5-element character array has been converted into this string: \"{0}\".", mystring);
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates using the overloaded string constructor of the form String(char[],int1,int2) to produce a new string formed of individual characters from the character array, starting at some particular position int1 and grabbing a total of int2 characters.
using System;
class Program{
static void Main(){
char[] mychararray = new char[11]{'N','e','w','Y','o','r','k','C','i','t','y'};
string mystring = new string(mychararray,3,4);
Console.WriteLine(mystring);
Console.ReadLine();
}//end Main
}//end class Program
Demonstrates one possible use of the @ symbol in regards to string.
using System;
class Program {
static void Main() {
string str =
@"I'm so happy to be a string
that is split across
a number of different
lines.";
Console.WriteLine(str);
Console.ReadLine();
}
}
Demonstrates that cloning a string returns a reference to that string instance, which can be assigned to another string, giving that other string a reference to the exact same location in memory.
using System;
class Program {
static void Main() {
bool test = false;
string s1 = "William";
string s2 = "Bryan";
string s3 = "Miller";
Console.WriteLine("s1 = {0}, s2 = {1}, s3 = {2}\n", s1, s2, s3);
s2 = (string)s1.Clone(); //now s2 references the same string instance that s1 does
Console.WriteLine("s2 = (string)s1.Clone(); //now s2 references the same string instance that s1 does\n");
test = SameValue(s1, s2);
if (test) {
Console.WriteLine("s2 now holds the same value that s1 holds, i.e., \"{0}\"\n", s1);
}
test = ReferencesSameObject(s1, s2);
if (test) {
Console.WriteLine("s1 and s2 reference the same instance object.\n");
}
s2 = s3;
Console.WriteLine("s2 = s3; // now s2 = {0} and s3 = {1}\n", s2, s3);
test = SameValue(s2, s3);
if (test) {
Console.WriteLine("s2 and s3 now hold the same value\n");
}
test = ReferencesSameObject(s2, s3);
if (test) {
Console.WriteLine("s2 and s3 now reference the very same instance.");
} else {
Console.WriteLine("s2 and s3 do NOT reference the same instance.");
}
Console.ReadLine();
}//end Main
private static bool SameValue(object o1, object o2){
if (o1.Equals(o2)) {
return true;
} else {
return false;
}
}
private static bool ReferencesSameObject(object o1, object o2) {
if (Object.ReferenceEquals(o1, o2)) {
return true;
} else {
return false;
}
}
}
Demonstrates that copying a string creates a new instance of a string by copying an existing instance.
// Sample for String.Copy()
using System;
class Sample {
public static void Main() {
string str1 = "abc";
string str2 = "xyz";
Console.WriteLine("1) str1 = '{0}'", str1);
Console.WriteLine("2) str2 = '{0}'", str2);
Console.WriteLine("Copy...");
str2 = String.Copy(str1);
Console.WriteLine("3) str1 = '{0}'", str1);
Console.WriteLine("4) str2 = '{0}'", str2);
}
}
/*
This example produces the following results:
1) str1 = 'abc'
2) str2 = 'xyz'
Copy...
3) str1 = 'abc'
4) str2 = 'abc'
*/
Demonstrates comparison of one string to another.
using System;
public class Program {
public static void Main() {
string s = "www.donationcoder.com";
string t = "www.donationcoder.com";
int i = s.CompareTo(t);
Console.WriteLine();
Console.WriteLine("\ts = \"{0}\"", s);
Console.WriteLine("\tt = \"{0}\"", t);
Console.WriteLine("\ti = s.CompareTo(t);");
Console.WriteLine("\ti = {0}.", i.ToString());
Evaluation(i);
Console.WriteLine();
s = "http://www.donationcoder.com";
i = s.CompareTo(t);
Console.WriteLine("\ts = \"{0}\"", s);
Console.WriteLine("\tt = \"{0}\"", t);
Console.WriteLine("\ti = {0}.CompareTo({1});",s,t);
Evaluation(i);
Console.WriteLine();
s = "C#";
t = "Ada";
i = s.CompareTo(t);
Console.WriteLine();
Console.WriteLine("\ts = \"{0}\"", s);
Console.WriteLine("\tt = \"{0}\"", t);
Console.WriteLine("\ti = s.CompareTo(t);");
Console.WriteLine("\ti = {0}.", i.ToString());
Evaluation(i);
Console.ReadLine();
}
private static void Evaluation(int i) {
if (i == 0) {
Console.WriteLine("\ts is equal to t.");
} else if (i < 0) {
Console.WriteLine("\ts is less than t.");
} else {
Console.WriteLine("\ts is greater than t.");
}
}
}
Demonstrates use of String.CopyTo().
using System;
class Program {
static void Main(string[] args) {
string s = "DonationCoder";
char[] mychar = new char[15];
s.CopyTo(0, mychar, 0, 8);
foreach (char c in mychar) {
Console.Write(c);
}
int i = mychar.GetUpperBound(0);
Console.WriteLine("Printed {0} characters, {1} of which were blank", i.ToString(), (i - 8).ToString());
Console.ReadLine();
}
}
Demonstrates use of String.EndsWith().
using System;
class myProgram
{
public static void Main()
{
string[] names = new string[15];
int m = 0;
int p = 0;
names[0] = "Bryan Miller";
names[1] = "Josh Pike";
names[2] = "Judy James";
names[3] = "Cyndi McGaha";
names[4] = "Jenny Burton";
names[5] = "Randy Wheat";
names[6] = "Tim Ellis";
names[7] = "Latisha Hughes";
names[8] = "Paula Miller";
names[9] = "Mindy Auberry";
names[10] = "Don McDaniel";
names[11] = "Allan Miller";
names[12] = "Kristen Pike";
names[13] = "Herbie Pike";
names[14] = "Jason Pike";
Array.Sort(names);
Console.WriteLine();
foreach(string name in names){
Console.WriteLine(name);
if(name.EndsWith("Miller")){
m++;
}
if(name.EndsWith("Pike")){
p++;
}
}
Console.WriteLine("\nNumber of Millers in names array: {0}",m.ToString());
Console.WriteLine("\nNumber of Pikes in names array: {0}\n",p.ToString());
Console.WriteLine("Press the Enter key to exit program... ");
Console.ReadLine();
}
}//end class myProgram
Demonstrates usage of the String.Equals() method
using System;
class Program{
static void Main(){
string pw = "donationcoder";
Console.Write("What is the password? ");
string answer = Console.ReadLine().Trim().ToLower();
if(answer.Equals(pw)){
Console.Write("Your password is correct!");
}else{
Console.Write("Wrong! You've been locked out of the database!");
}
Console.ReadLine();
}
}
Demonstrates usage of the String.Substring() and String.IndexOf() methods
using System;
/*
* Written by Bryan Miller on March 30, 2007
* wmmiller@duo-county.com or kyrathaba@yahoo.com
* http://kyrathaba.dcmembers.com
* http://www1.webng.com/bowrsanryld/
*/
class Program {
static void Main(string[] args) {
string vowels = "AEIOUaeiou"; //the vowels
string currentLetter = string.Empty; //the character we're currently examining in the word
string word = string.Empty; //the word entered by the user
int wordlen = -1; //will hold length of word entered by user
int index = -1; //will hold value corresponding to current position that we're evaluating within the word
Console.WriteLine("For our purposes, \"Y\" is not considered among the vowels...\n");
//unless and until user enters the word "quit", do all this...
do {
//ensure that user enters a string of characters whose length is between 3 and 15, inclusive
do {
Console.WriteLine("Please enter a word that is 3 to 15 characters long, ");
Console.Write("or enter \"quit\" to exit program: ");
word = Console.ReadLine().Trim();
wordlen = word.Length;
Console.WriteLine();
if (wordlen < 3) { Console.WriteLine("Your word should be at least 3 characters in length.\n"); } //end if
if (wordlen > 15) { Console.WriteLine("Your word should be no more than 15 characters in length.\n"); } //end if
} while ((wordlen < 3) || (wordlen > 15)); //end do-while
/*
* The following for loop steps through the individual letters of the word entered by the user, beginning with the
* first letter of that word and, if necessary, going all the way to the last letter. For each letter in the word,
* we use the .IndexOf String instance method to determine if that letter is a vowel or not. If it IS, we set our
* integer variable named index equal to i, and since i is the index of the current letter we're examining, index
* will -- as we break out of the for loop -- hold the index at which the first vowel occurs in the word. We could
* have completed the for loop, stepping through each and every element of the word. But if the first vowel doesn't
* occur at the very last position in the word, it would be inefficient. Better to break out of the for loop as soon
* as we have located the very first vowel.
*/
for (int i = 0; i < wordlen; i++) {
currentLetter = word.Substring(i, 1);
index = vowels.IndexOf(currentLetter);
if (index != -1) {
index = i;
break;
}//end if
}//end for loop
/* if the word the user entered is "quit", then user wants to exit program and isn't interested in the information
* contained in the following Console.WriteLine() invocations */
if (word != "quit") {
if (index != -1) {
Console.WriteLine("The first vowel, \"{0}\", occurred at position {1} in \"{2}\"", currentLetter, index, word);
Console.WriteLine("It is the {0}", PositionOfLetter(index,wordlen));
} else {
Console.WriteLine("There were no vowels found, therefore the string you entered");
Console.WriteLine("cannot properly be called a word.");
}//end if
}//end if
Console.WriteLine();
} while (word.ToLower() != "quit"); //end outer do-while
}//end Main
private static string PositionOfLetter(int index, int wordlen) {
/*
* The 0th position is the word is the 1st character. The 4th position is the 5th character, etc.
* This switch statement maps this relationship, and allows us to build up the returnVal string as
* a return value, making this private static method useful to the program's output
*/
string returnVal = string.Empty;
switch (index) {
case 0:
returnVal = "1st";
break;
case 1:
returnVal ="2nd";
break;
case 2:
returnVal ="3rd";
break;
case 3:
returnVal ="4th";
break;
case 4:
returnVal = "5th";
break;
case 5:
returnVal = "6th";
break;
case 6:
returnVal ="7th";
break;
case 7:
returnVal ="8th";
break;
case 8:
returnVal ="9th";
break;
case 9:
returnVal ="10th";
break;
case 10:
returnVal ="11th";
break;
case 11:
returnVal ="12th";
break;
case 12:
returnVal = "13th";
break;
case 13:
returnVal ="14th";
break;
case 14:
returnVal ="last";
break;
default:
returnVal ="unknown error in switch statement";
break;
}//end switch
returnVal += " of " + wordlen.ToString() + " characters in the word";
return returnVal;
}//end private static string method
}//end class Program
Demonstrates usage of the String.LastIndexOf() instance method
using System;
class Program {
static void Main(string[] args) {
string s = "Mississippi";
int i = s.LastIndexOf("i");
Console.WriteLine("\n\t\"Mississippi\" has {0} letters in it, and the last \"i\" occurs at index {1}.",s.Length.ToString(),i.ToString());
i = s.LastIndexOf("s");
Console.WriteLine("\tThe last \"s\" occurs at index {0}", i.ToString());
i = s.LastIndexOf("p");
Console.WriteLine("\tThe last \"p\" occurs at index {0}", i.ToString());
Console.ReadLine();
}
}
Demonstrates usage of the String.PadLeft() instance method
using System;
class Program {
static void Main(string[] args) {
double sdoub = 80.01;
double tdoub = 5000.11;
double xdoub = 440.73;
double ydoub = 95473.82;
double sum = sdoub + tdoub + xdoub + ydoub;
string s = sdoub.ToString().PadLeft(9);
string t = tdoub.ToString().PadLeft(9);
string x = xdoub.ToString().PadLeft(9);
string y = ydoub.ToString().PadLeft(9);
string z = new string('-', 9);
string strsum = sum.ToString().PadLeft(9);
s = s.PadLeft(9);
t = t.PadLeft(9);
x = x.PadLeft(9);
Console.WriteLine(s);
Console.WriteLine(t);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(strsum);
Console.ReadLine();
}
}
Demonstrates usage of the String.Split() instance method
using System;
class Program {
static void Main(string[] args) {
//first, create the original sentence
string sentence = "The DonationCoder site is an excellent forum for software connoisseurs.";
/* then, set up a blank space as the delimiter, since each word in the sentence has a blank space
* separating it from adjacents words */
char delimiter = ' ';
/* Now for the workhorse line of code in this program: we create a string array (yes, I know we
* haven't covered arrays yet) that will hold the words of the sentence. We then use the Split
* method on our string instance, specifying a character delimiter so that the method knows where
* to break the sentence into pieces */
string[] words = sentence.Split(delimiter);
//show user the original sentence
Console.WriteLine("Original sentence: {0}\n", sentence);
/* Use a foreach loop to step through each element of the string array named words */
foreach (string word in words) {
Console.WriteLine(word);
}
Console.ReadLine(); //to pause execution so user can view the console
}
}
Demonstrates usage of the String.Join() static String method
using System;
class Program {
static void Main(string[] args) {
string[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
string year = string.Join("/", months);
Console.WriteLine(year);
Console.ReadLine(); //to pause execution so user can view the console
}
}
Demonstrates usage of the StringBuilder() class
using System;
using System.Text;
class Program {
static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
sb.AppendFormat("\n{0,-25}{1,3}\n\n", "Name", "Age");
sb.AppendFormat("{0,-25}{1,3}\n", "Seth", 6);
sb.AppendFormat("{0,-25}{1,3}\n", "Emily", 7);
sb.AppendFormat("{0,-25}{1,3}\n","Paula Miller", 60);
sb.AppendFormat("{0,-25}{1,3}\n", "Methuselah", 927);
sb.AppendFormat("{0,-25}{1,3}\n", "William Bryan Miller", 35);
sb.AppendFormat("{0,-25}{1,3}\n", "Michael Allan Miller", 34);
sb.AppendFormat("{0,-25}{1,3}\n", "Margaret Ellen Jones", 29);
sb.AppendFormat("{0,-25}{1,3}\n", "Lauren Danielle Jones", 6);
Console.WriteLine(sb);
sb.EnsureCapacity(sb.Length);
Console.WriteLine("capacity = {0}, length = {1}", sb.Capacity, sb.Length);
Console.ReadLine();
}
}