Substring from List of strings

Hi there,

I have a List of strings and I should get a substring out of it.

e.g.

List myListOfStrings = new List () {
"1234567890",
"2345678901",
"3456789012",
"4567890123",
"5678901234"
};

The above list should become something like this, cutting of the 4 first chars and the last 2:

            "5678", 
            "6789", 
            "7890", 
            "8901",
            "9012"

How can I do that, prefarably in one loop ? Thanks for your help !!

Posts

  • JeffreyStedfastJeffreyStedfast USXamarin Team Xamurai

    Give this a try:

    var substrings = new string[myListOfStrings.Count];
    for (int i = 0; i < myListOfStrings.Count; i++)
        substrings[i] = myListOfStrings[i].Substring (4, myListOfStrings[i].Length - 6);
    
  • jaYCee.1750jaYCee.1750 USMember ✭✭

    What if the length of the strings aren't equal with each others? Like...

        List myListOfStrings = new List () { 
        "4567890", 
        "2345678901", 
        "56789012", 
        "567890123",
        "01234"
        };
    

    And what you want is that to output the last 4 digits? Like...

    7890
    8901
    9012
    0123
    1234

  • JGoldbergerJGoldberger USXamarin Team, University Xamurai
    edited October 17

    @jaYCee.1750

    Give this a try:

        var substrings = new string[myListOfStrings.Count];
        for (int i = 0; i < myListOfStrings.Count; i++) 
                substrings[i] = myListOfStrings[i].Substring(myListOfStrings[i].Length - 4);
    

    the API docs for Substring would have helped you here:
    Overload 1: https://msdn.microsoft.com/en-us/library/hxthx5h6(v=vs.110).aspx
    Overload 2: https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx

    Overload one takes one argument which is the start point of the substring. So in the above example code I used this overload to say "give me the substring that starts 4 characters before the end of the string and goes to the end of the string."

    Overload 2 takes two arguments, a start and a length. To use overload 2, you could do:

        substrings[i] = myListOfStrings[i].Substring(myListOfStrings[i].Length - 4, 4);
    

    Which will also give you the last 4 characters regardless of string length. However if you do either of the above on a string with less than 4 characters, you will get an error, so if you are unsure about how long a string is, do a test before calling the SubString method, or catch any ArgumentOutOfRangeException and handle it.

    I am going to close theis thread as this is not a Xamarin question at all, but a generic .NET framework question. Stack overflow would be a better place for this sort of question

This discussion has been closed.