練習4:將字串第一個字母轉換成小寫
撰寫一個函數,接收一個字串,把用戶輸入字串的第一個字母轉換成小寫,然後返回(命名規範:駱駝命名) name s.SubString(0,1) s.SubString(1)
1
2
3
4
5
6
7
8
9
string s = "AAbc";
string newStr = ProcessStr(s);
Console.WriteLine(newStr);
static string ProcessStr(string str)
{
string s = str.Substring(0, 1).ToLower(); //取第一個字母轉換成小寫
return s + str.Substring(1); //組裝:s+從第二個字開始取
}
練習5:將字串第一個字母轉換成大寫
撰寫一個函數,接收一個字串,把用戶輸入字串的第一個字母轉換成大寫,然後返回(命名規範:帕斯卡) name s.SubString(0,1) s.SubString(1)
1
2
3
4
5
static string ProcessStr(string str)
{
string s = str.Substring(0, 1).ToUpper(); //取第一個字母轉換成大寫
return s + str.Substring(1); //組裝:s+從第二個字開始取
}
練習6:交換兩變數(不使用第三個變量交換)
聲明兩個變量:int n1 =10 int n2 =20,將兩個變量交換,最後輸出n1=20 n2=10,不使用第三個變量交換
使用第三方變數
1
2
3
4
5
int n1 = 10;
int n2 = 20;
int temp = n1;
n1 = n2;
n2 = temp;
不使用第三方變數
1
2
3
4
5
int n1 = 10;
int n2 = 20;
n1 = n1 - n2;//n1=-10,n2=20
n2 = n1 + n2;//n1=-10,n2=10
n1 = n2 - n1;//n1=10-(-10)=20
練習7:用ref參數方法實現交換兩變數
使用ref參數方法,ref值傳遞變成引用傳遞。
使用ref參數將值帶入方法中,運算後的結果會帶出方法。
傳地址進去,它們在Stack(堆疊/棧)是同一個內存,你改變其中一個,另一個也會改變
1
2
3
4
5
6
7
Swap(ref n1, ref n2);
static void Swap(ref int n1, ref int n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}