亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取字符串中的特定字符?

如何獲取字符串中的特定字符?

C#
斯蒂芬大帝 2021-11-07 18:41:41
我有一個問題,我需要遍歷一個字符串并單獨打印每個字符:var abc = MyFunction('abc')abc() // should return 'a' on this first callabc() // should return 'b' on this second callabc() // should return 'c' on this third callabc() // should return 'a' again on this fourth call
查看完整描述

1 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

你真的應該澄清你遇到的問題;請隨時閱讀如何提問。


基本循環


就您的問題而言(根據我的理解),您希望重復調用一個方法并讓該方法返回與當前調用對應的字符串的索引。我會查看for 循環和string.Substring(int),您也可以將字符串作為字符數組訪問(我在下面這樣做)。


static void Main() {

    string myString = "SomeStringData";

    for (int i = 0; i < myString.Length; i++)

        Console.Write(GetCharacter(myString, i));

}

static char GetCharacter(string data, int index) => data[index];

可以修改上面的代碼以進行順序調用,直到您需要停止循環,這將滿足到達字符串末尾后返回第一個索引的條件:


string myString = "abc";

for (int i = 0; i < myString.Length; i++) {

    Console.Write(GetCharacter(myString, i);


    // This will reset the loop to make sequential calls.

    if (i == myString.Length)

        i = 0;

}

如果您想逃避上面的循環,您需要添加一些條件邏輯來確定循環是否應該被破壞,或者只對GetCharacter(string, int)提供的方法進行單獨調用而不是循環。此外,i如果確實需要,您應該只修改迭代變量;在這種情況下,您可以切換到更合適的while 循環:


string myString = "abc";

string response = string.Empty;

int index = 0;

while (response.TrimEnd().ToUpper() != "END") {

    Console.WriteLine(GetCharacter(myString, index++));

    Console.WriteLine("If you wish to end the test please enter 'END'.");

    response = Console.ReadLine();


    if (index > myString.Length)

        index = 0;

}

獲取角色(表情身體 vs 全身)


C# 6 引入了將方法編寫為表達式的能力;寫成表達式的方法稱為Expression-Bodied-Member。例如,以下兩種方法的功能完全相同:


static char GetCharacter(string data, int index) => data[index];

static char GetCharacter(string data, int index) {

    return data[index];

}

表達式主體定義允許您以非常簡潔、易讀的形式提供成員的實現。只要任何受支持成員(例如方法或屬性)的邏輯包含單個表達式,就可以使用表達式主體定義。


查看完整回答
反對 回復 2021-11-07
  • 1 回答
  • 0 關注
  • 484 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號