Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Strings And Arrays: A Simple Commented Example
12-16-2009, 09:12 AM (This post was last modified: 12-16-2009 09:16 AM by Back_track.)
Post: #1
Strings And Arrays: A Simple Commented Example
Code:
using System;
using System.Collections.Generic;
using System.Text;

namespace Array_String
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter In Your String");//Prompt User
            string STR = Console.ReadLine();//Creates string variable
            Console.WriteLine("Enter in The Number of the Array Index you want displayed");
            int ind = Int32.Parse(Console.ReadLine());//integer "ind" is Console.ReadLine(User Input)

           if (ind > STR.Length - 1 )//if the integer is larger than the string's length
                {
                    Console.WriteLine("Your Array Index is out of bounds");//Say it is
                    System.Threading.Thread.Sleep(1000);//Wait a bit
                    Environment.Exit(1);//Exit
            }
            
            {


            }
            Console.WriteLine(STR[ind]);//write the strings array index value for example [2]
            Console.ReadLine();//Wait for Enter Key
        }
    }
}
Example Input:
Enter In Your String
Hello
Enter in The Number of the Array Index you want displayed
0
H
Notes
I compare the Indexes Number to the Strings Length and subtract one because the array index starts from 0

"Character is determined more by the lack of certain experiences than by those one has had."
Friedrich Nietzsche
Visit this user's website Find all posts by this user
Quote this message in a reply
12-17-2009, 04:47 AM
Post: #2
RE: Strings And Arrays: A Simple Commented Example
Very easy and structured. It is good that you put condition. But this program doesn't cover everything. What if I enter negative number for example -1.
So if it is bigger than string length or smaller than zero.
Except this line:
Code:
if (ind > STR.Length - 1 )
you could add this :
Code:
if (ind > STR.Length - 1 || ind<0)

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: