How to check the last character of a string in C#?

后端 未结 3 1169
深忆病人
深忆病人 2021-02-06 23:58

I want to find the last character of a string and then put in an if stating that if the last character is equal to \"A\", \"B\" or \"C\" then to do a certain action

相关标签:
3条回答
  • 2021-02-07 00:17

    Use the endswith method of strings:

    if (string.EndsWith("A") || string.EndsWith("B"))
    {
        //do stuff here
    }
    

    Heres the MSDN article explaining this method:

    http://msdn.microsoft.com/en-us/library/system.string.endswith(v=vs.71).aspx

    0 讨论(0)
  • I assume you don't actually want the last character position (which would be yourString.Length - 1), but the last character itself. You can find that by indexing the string with the last character position:

    yourString[yourString.Length - 1]
    
    0 讨论(0)
  • 2021-02-07 00:32

    string is a zero based array of char.

    char last_char = mystring[mystring.Length - 1];
    

    Regarding the second part of the question, if the char is A, B, C

    Using if statement

    char last_char = mystring[mystring.Length - 1];
    if (last_char == 'A' || last_char == 'B' || last_char == 'C')
    {
        //perform action here
    }
    

    Using switch statement

    switch (last_char)
    {
    case 'A':
    case 'B':
    case 'C':
        // perform action here
        break
    }
    
    0 讨论(0)
提交回复
热议问题