Solution - Challenge Phun With Strings

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

Get GitHub Code

This is the solution for the challenge called ChallengePhunWithStrings, where you are required to complete a series of four tasks, each involving string manipulation. We'll break down the solution into sections for each task. Make sure to comment out the code for the previous challenge before moving on to the next.

Challenge 1

Step 1: Open the ChallengePhunWithStrings Project in Visual Studio

Begin by navigating in your Windows directory to the CS-ASP_035-Chalenge_Code file, where you'll find the ChallengePhunWithString.sln file:


Open that file up in Visual Studio, and you'll be supplied with the instructions for the different challenges, as well as starting code. At the top of the Default.aspx.cs page, you'll see the following code and instructions:


Step 2: Set Up a Reverse For() Statement

What you need to do is reverse the string so that it prints out in reverse. To do this, you'll use a for() statement to loop backwards through the string, printing out each letter as it goes. To do this, you'll need to access the length of the string, using the Length property, then iterate backwards:


Notice that most of the syntax in this for() statement is reversed from what we normally see; instead of the condition being i < Length, it's changed to i >= 0 and i decrements instead of incrementing up. This is the format used whenever you want to loop through something right-to-left or greatest to least.

Step 3: Accessing the Indexes of the String

If you recall from the lesson on string formatting, strings are considered to be an array of individual letters, which means we can loop through the string by accessing each individual element in that array and printing it to the resultLabel:


However, one important change needs to be made to the for() statement: Instead of checking against name.Length, we have to check against name.Length - 1, or else we will receive an index out of range exception. Remember, we're treating the string as an array of characters and since arrays are zero-based, the highest index value of the array will be one less than its length:


Save and run your project to see the result:


Challenge 2

Step 1: Split the String

Since this challenge requires you to take a set of names and reverse the order in which they appear, we'll need to separate each name into its own array index. To do this, create a new string array called rebelScum:


Now that we've declared the array, let's populate it with the names in the string we were given. To do this, we'll make use of the Split() method for the string class, and we'll separate the string at the commas:


Note that we can both create and populate the array in the same line of code, which what was done here by simply modifying the declaration statement. What this code does, in essence, is breaks the string into different sections, here determined by the location of commas, then populates the array with those values.

Step 2: Iterating through the Array

Next, declare a new string called result, setting it equal to an empty string. We'll use that to store our text before sending it to the resultLabel. Now that we have a populated array, we can use the same logic as our previous for() statement to iterate through the array in reverse. This time, instead of adding to the resultLabel, we'll add the current index to the string result, then add on the comma:


Outside the for() statement, we need to make an adjustment in order to remove the last comma that was placed by our code. In order to do this, we'll use the Remove() method, pulling off one character from the end of the string:


Now, simply set the resultLabel's text equal to result. Save and run your project and see what's printed out:


Challenge 3

Step 1: Create an Array of String

This challenge requires you to add ascii art to both sides of a series of given names (the same variable for the previous challenge, don't comment that line out). The total number of characters should add up to 14 after the art is added. To do this, we'll create an array of string called rebelScum, following the same method as before to populate the array:


Step 2: Planning the Code

In order to proceed, we will create a for() statement to iterate through the array as we've done before, except this time it will not be in reverse:


Inside this for() statement, the goal is to evaluate every name, or index, to determine how much padding to add to each. How will we find this out? We know that the total number of characters needs to equal 14, and we can also access the length of the index we're evaluating. What needs to be done is to subtract the length of the index from the total length (14) to determine the total number of asciis.

To illustrate this, let's evaluate the name "Luke". The length of Luke is 4, which we'll subtract from 14, leaving us with 10. This gives us the total number of asciis. To determine how many on each side, we'll divide 10 by 2, leaving us with 5. Then we could simply set the PadLeft and PadRight values to 5.

This works fine when the number can divide evenly in, but say we had 9 after subtracting from 14, how would we do that? There's no even way to divide the number in two. Since we need whole numbers, we'd create an int variable to hold the total number of asciis on one side (let's call it padLeft). By using an integer value, we know that the decimal place will be truncated, leaving us with a whole number, in this case 4. Now, we can add padLeft's value to rebelScum[i] in order to determine how many characters are needed on the right. We assign a temporary variable to hold the new value with the ascii's on the left, then call the PadRight() method on that variable to add the remaining number needed.

Step 3: Implementing the Plan

Now that we have a working plan, let's see how this might look in code. Note that the code reads a little differently than what the laid out plan said, but it follows the method described:


Let's take a moment to go through and explain exactly how this works.

  1. The rebelScum array is initialized and populated with the names
  2. A temporary string result variable is created to hold the information at the end of each iteration
  3. The for() statement is set, resulting in an iteration through the array
  4. An integer variable called padLeft is created to determine the number of asciis on the left side
  5. A string variable called temp is created and set to the value of rebelScum[i] after the PadLeft() has been applied
  6. The temp variable has the ascii's appended to is, then is added to the result
  7. A break line is added to the result, so that the names are on separate lines
  8. The resultLabel is set to the final value of result, after the iterations are complete.

Save and run your code to see the result:


Challenge 4

Step 1: Break the Problem into Tasks

Moving onto the fourth challenge, you need to take a string called puzzle and modify its contents to say, "Now is the time for all good men to come to the aid of their country." However, as you can see, the puzzle string is nearly all caps, the letter 't' is replaced with 'z', and there's a section that says 'remove-me'. To format this, we'll need to utilize several different methods in different steps.

The easiest step to take first would be to remove the text 'remove-me' from the string. Once that's done, we can change the casing of the string to lower case. After that, we can replace the 'z' characters in the string.

Step 2: Removing Text from the String

The first modification we'll make to this string is to remove the text 'remove-me' from it. In order to do this, we'll use the Remove() method of the String class. This method has input parameters for the starting index and the number of characters to remove from the string. In order to get the starting index, let's create a string called removeMe and set it equal to the text we need to remove:


Now that we have that string, we can use it to determine the index position of puzzle that matches its value:

Finally, we can set puzzle equal to puzzle.Remove(), passing in the index and removeMe.Length as the input parameters for the method:


Step 3: Adjusting the Casing

Because the string is in all capital letters, we need to format it so that it reads like you would in English; with a capitalized first letter and the rest lower-case. The easiest way to do this is to set puzzle equal to puzzle.ToLower(). However, this will cause the entire string to be lower-case, including the first letter. To fix this, we'll remove the first letter and then insert the correct letter in its place:


In order to test this, set the resultLabel's text equal to puzzle. Then, save and run the project to see the result:


Step 4: Replacing Letters

All that remains for this challenge is to replace all the 'z' characters with the letter 't'. Fortunately, the string class has a Replace() method which takes in the character to be replaced, as well as the character it needs to be replaced with. In this case, we'll use puzzle.Replace, passing in 'z' and 't' respectively:


Once again, save and run the project to see the result:



This completes ChallengePhunWithStrings. There were several different methods to implement and different logic to use depending on the situation. Hopefully you see that most of the work is in thinking through the problem, breaking it down and then tackling individual steps. If you did not complete this on your own, come back and try again at a different time. Modify the challenge if you'd like to learn more about different methods you can use on the string class. The more you code, the more effectively you'll learn the concepts. You're doing a great job, keep it up!

Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment