02-C # Getting Started (enumeration, structure, etc)

Source: Internet
Author: User

Do not study for writing notes !!!

). Of course, the value of review is worth time.

  • Enumeration and Structure

The enumerated types are limited (short, byte...) and are the same. Find some examples of enumeration on MSDN and think this is not bad:

        enum myWeekDay { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };        int i = 3;        myWeekDay today = (myWeekDay)i;

Enumeration needs to be declared first, and then used by creating a new variable (today) as the enumeration type. The default basic type value of enumeration starts from 0 and increments by 1. This is calledEquality Series.

Enumeration DeclarationIt is recommended to put it in the namespace, of course, it can also be placed in the class or structure. When assigning other variables to enumeration types, you need to forcibly convert them, for example, today = (myWeekDay) myByte. Of course, there is also the Enum. Parse (typeof (),) command, so we will not study it in detail. Let's take a look at it later.

WhileStructure ()It is easy to use. A structure supports different basic data types. You also need to declare the structure first, and then declare the variable as the structure type to use:

    enum orientation : byte { north = 1, south = 2, east = 3, west = 4};    struct route    {        public orientation direction;        public double distance;    }

Use public: allow the code that calls this structure to access members of this structure. Specific applications:

Route myRoute; int myDirection =-1; double myDistance; Console. writeLine ("1) North \ n2) South \ n3) East \ n4) West"); do {Console. writeLine ("select a direction:"); myDirection = Convert. toInt32 (Console. readLine ();} while (myDirection <1 | myDirection> 4); Console. writeLine ("enter a distance:"); myDistance = Convert. toDouble (Console. readLine (); myRoute. direction = (orientation) myDirection; myRoute. distance = myDistance; Console. writeLine ("the distance to {0} in the specified direction is {1}", myRoute. direction, myRoute. distance );

Note that the line of myRoute. direction = (orientation) myDirection code should beEnumeration application scenarios: You only need to specify the basic type value I in the enumerated value, and then use (enumName) I to obtain the corresponding string.

Declare a structure:Route (created structure name) myRouteAnd then passMyRoute. AttributesAccess the members in the structure.

  • Array

Arrays in impressions are always complicated. A good example: You need to store the names of 10 students. You can simply solve this problem by using arrays. First, declare the array:

String [] friendNames = new string [arrayCount]; string [] friendNames = {"Zhang San", "Li Si", "Wang Wu", "Xie Liu", "Chen Qi "};

The first line onlyInitialize the array size, OptionalConstantOrConstantAfter initialization, you can use the friendNames [0] method to assign values to array elements. The second line directly declares the array and initializes the content of the array.

You can use the for loop and the size of friendNames. Length to access the array value. Note that the position of the 1st elements is 0. You can also use foreach without worrying that it is out of the array range. The difference between foreach and for is that foreach is read-only.

foreach (string myStr in friendNames){    Console.WriteLine(myStr);}

Multi-dimensional arrays are divided into rectangular arrays () and sawtooth arrays (). Of course, you can also use the foreach method to retrieve the content of all elements and nest a foreach:

            int[][] jaggedIntArray = { new int[] { 1, 2, 3 }, new int[] { 4, 5 }, new int[] { 6, 7, 8, 9 }, new int[] {10, 11} };            foreach(int[] topArray in jaggedIntArray)            {                foreach (int bottomArray in topArray)                {                    Console.Write("{0} ", bottomArray);                }                Console.Write("\n");            }

Note:[] Or {} is used here, and no () method is used. Do not always write wrong brackets, which is very low-level.

  • String processing

This is much more interesting. You can use myString [1] to access each character in the string. The 1st characters are 0:

String myString = "  HeLlO WoRlD ";char myChar = myString[1];

Use ToCharArray () to obtain a char array after each character of myString is decomposed:

char[] myChars = myString.ToCharArray();

You can also use myString. Length to obtain the number of strings, use myString. ToLower () to convert to uppercase, and convert myString. ToUpper () to lowercase. Note:ToLower () and ToUpper () do not change the case sensitivity of the variable. You also need to use myString = myString. ToLower () to modify the value of the variable itself.

MyString. Trim () removes spaces before and after the string, TrimStart () and TrimEnd (), respectively. You can also use Trim (myChar []) to specify whether the content before and after removal is not limited to spaces (char [] myChar = {'','s '}):

            myString = "  sfrost/110110200010101100-13090909880 ";            char mykg = ' ';            char[] myxhx = {'-','/'};            String[] myStrings = myString.Trim(mykg).Split(myxhx);            Console.WriteLine("myStrings[0] = {0}", myStrings[0]);            Console.WriteLine("myStrings[1] = {0}", myStrings[1]);            Console.WriteLine("myStrings[2] = {0}", myStrings[2]);

Recently, I was just engaged in development. In C #, In the above example, I can use a (some) keyword to break down the personal information entered by the user. The Split () method used in this example can also use a char array to indicate the identifier of the decomposition.Note that the position of the Split string can be multiple marked positions.

  • Conclusion

Starting from this chapter, you can do a lot of things right away. Whether it is enumeration (), structure (), array (), and string processing, how to convert values between enumeration and common variables, how to declare, initialize, and access arrays, etc. The processing of strings is too interesting, especially split, replace, and then apply the char array.

  • Appendix: Exercise Cases

Write a console application that receives the string entered by the user and outputs the string in the reverse direction of the input:

Console. writeLine ("Enter the String to be switched:"); String myString = Console. readLine (). trim (); Console. writeLine ("{0}", myString. length); String tmpStr = ""; for (int I = myString. length; I> 0; I --) {tmpStr + = myString [I-1];} Console. writeLine (tmpStr );

Write a console application that receives user input strings and replaces all the no in the string with yes:

Console. writeLine ("enter a string with no:"); myString = Console. readLine (). toLower (). trim (); Console. writeLine ("Replace no in {0} with yes: {1}", myString, myString. replace ("no", "yes "));

Write a console application to enclose every word in the string with quotation marks (I think there must be spaces between words ):

Console. writeLine ("Enter the word with spaces:"); String myWord = Console. readLine (). trim (); String [] myWords = myWord. split (''); myWord =" "; foreach (String tmpWord in myWords) {myWord + =" \ "" + tmpWord + "\" ";} Console. writeLine ("sentence after quotation marks: {0}", myWord );

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.