C# Getting Started 2

table of Contents

Type conversion

Implicit

display

Advanced variables

enumerate

structure

Array

String processing

Modify a single character

Replacement text

Delete text

Remove spaces

Add space

Replace case


This article mainly introduces advanced variable types

 

Type conversion

Implicit

The values ​​in Type A are included in Type B, and A can be implicitly replaced with Type B

display

  1. Type conversion pay attention to whether the value has overflow, you can use checked/unchecked keywords, such as checked((byte)var) if there is overflow, an error will be reported
  2. Type conversion functions in Convert

Advanced variables

enumerate

Use enum to define enumeration variables

enum<typeName>
{
    <value1>,
    <value2>,
    ...
    <valueN>
}

statement

<typeName> <varName>;

Assignment

<varName> = <typeName>.<value>;

The default basic storage type of enumeration is int, if you want to specify other basic types, you can add the type in the declaration

enum<typeName>:<underlyingType>
{
    <value1>;
    <value2>;
    ...
    <valueN>
}

By default, the value associated int defined by the enumeration starts from 0 and increases by 1 in the text order, and <value2>=<value1>+1. The assignment process can also be overridden. Use = to specify the actual value of each enumeration

enum<typeName>:<underlyingType>
{
    <value1>=<actualVal1>;
    <value2>=<actualVal2>;
    ...
    <valueN>=<actualValN>;
}

structure

Use struct to define structure

struct<typeName>
{
    //<memberDeclatations>
    <accessibility> <type> <name>;
}

//定义结构变量
<typeName> name;


//实例
struct route
{
    public orientation direction;
    public double distance;
}

//定义结构变量
route myRoute;

Array

statement

<baseType>[] <name>;

There are two ways to initialize an array:

  1. Literal value specifies the complete content
  2. Use the new keyword to initialize all array elements after specifying the array size
//字面值指定
int[] myIntArray = {5,9,10,2,99};

//new初始化
int[] myIntArray = new int[5];

Note:

  1. Using new to display the initialization array will assign the same default value to all array elements, and the value type is 0
  2. Initialize with non-constant variables
  3. When the two methods are combined, the variable must be a constant, and the assignment element must be the same size as specified by new
//非常量初始化
int arraySize = 5;
int[] myIntArray = new int[arraySize]

//两种结合
int[] myIntArray = new int[5]{1,2,3,4,5};

//下面是错误的
int[] muIntArray = new int[5]{1}; //大小不匹配

//除非arraySize声明为const否则是错误的
int[] myIntArray = new int[arraySize]{1,2,3,4,5}; 

array.Length can get the array size

Special array must be initialized before access, the following assignment is wrong

int[] myIntArray;
myIntArray[10] = 5;

foreach can access the array read-only

foreach(<baseType><name> in <array>)
{
    //can use <name> for each element
}

//实例
foreach(string firendName in firends)
{
    WriteLine(firendName);
}

Multidimensional Arrays

Statement: use, statement

//二维数组
<baseType>[,] <name>;
//四维数组
<baseType>[,,,] <name>;

Array initialization

//声明一个x*y的二维数组
<baseType>[,] <name> = new <baseType>[x,y]

int [,] location = new int[3,4]

//隐式表示大小~一个3*3大小的二维数组
int [,] location = {
   
   {1,2,3},{4,5,6},{7,8,9}};

Visit, specify each coordinate

location[1,1];

foreach traverses multi-dimensional arrays in the same way as one-dimensional

Array of arrays

Disclaimer: Use multiple []

<baseType>[][] <name>

int[][] data;

initialization

//基础
<name> = new <baseType>[x][];
<name>[0] = new <baseType>[y0];
...
<name>[N] = new <baseType>[yN];


//实例
data = new int[2][];
data[0] = new int[3];
data[1] = new int[4];

//也可以用字面值赋值
data = new int[2][]{
    new int[]{1,2,3},
    new int[]{4,5}
};

//隐式第一维初始化
int[][] data = {
    new int[]{1,2,3},
    new int{4,5}
};

The traversal of foreach is different from multidimensional arrays and usually requires nesting

foreach(int[] nums in data)
{
    foreach(int num in nums)
    {
        WriteLine(num);
    }
}

String processing

String can be regarded as a read-only array of char (ie, the string is immutable), and supports subscript access

string myString = "a string";
char myChar = myString[0];

Modify a single character

You cannot operate on the original string, you need to generate a character array from the string, modify the content in the array, and then create a new string from the modified content of the array. Use String.ToCharArray() method to create character array.

string myString = "a string";
char[] myChars = myString.ToCharArray();

Replacement text

Use the String.Replace() method to replace text. This method can replace a string or a single character, and every match of the search text is replaced. Note that the replacement will not change the original string. If you want to keep the changed string, you need to create a new string and save it.

string myString = "A string";
string myNewString = myString.Replace("A","New");

Note: You can refer to the related content of regular expressions for more advanced replacement search.

Delete text

Use the String.Remove() method to delete the text in the string. This method removes certain characters starting at a specific index.

string myString = "A string";
string removeString = "A";
int i = myString.IndexOf(removeString);
string result = string.Empty;
if(i>=0)
{
    result = myString.Remove(i,removeString.Length);
    //输出 string
    Console.WriteLine(result);
}

Note:

  1. String.IndexOf("str") method finds the starting index of str in string
  2. string.Length returns the number of characters in the string
  3. string.Empth returns an empty string

Remove spaces

Use String.Trim(), String.TrimStart(), String.TrimEnd() methods to delete the leading/ trailing spaces. Using this method, the original string content remains unchanged, and a new string needs to be created to retain the modified content. In addition, you can also specify to delete other leading or trailing characters.

string myString = "  A string  ";

//删除前/后置空格
string myNewString = myString.Trim();

//删除前置空格
string myNewString = myString.TrimStart();

//删除后置空格
string myNewString = myString.TrimEnd();

//删除其他字符,在一个char数组中指定
char[] trimChars = {' ','s'}
string myNewString = myString.Trim(trimChars);    //删除前后空格,字符s

Add space

Similar to the above, using the String.PadLeft() and StringPadRight() methods, you can add spaces around the string to make the string reach the specified length, or you can add specified characters, but use char characters instead of char arrays

string myString = "A string";
//在左边添加两个空格
myString = myString.PadLeft(10);
//在左边添加两个 - 
myString = myString.PadLeft(10,'-');

Replace case

Use String.ToLower() and String.ToUpper() methods to replace string case

string myString = Console.ReadLine();
if(myString.ToLower() == "yes")
{
     Console.WriteLine("yes");   
}
//使用上面的方法可以检查输入为 YES,Yes,yEs...等形式的字符串

 

Guess you like

Origin blog.csdn.net/wyzworld/article/details/112513407