简体   繁体   中英

C# Splitting another string

I am wanting to split the next string which is "L" but it is not working for some reason. I have managed to make this work for my first substring and it seems to be working but this is not working for my second substring which should return "L" within the console in a new line or the 20th character. Any ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace employeefinal
{
    class Program
    {
        static void Main(string[] args)
        {
            employee i = new employee();
            Console.WriteLine(i.getName());
            Console.ReadLine();
            Console.WriteLine(i.getCity());
            Console.ReadLine();


        }
        public class employee
        {
            string employeename = "Name:John How Smith L, U, 012, 2, 7, 2, 4";


            public employee()
            {

            }

            public string getName()
            {
                return employeename.Substring(0, 19).Trim();
            }

            public string getCity()
            {
                return employeename.Substring(19, 20).Trim();
            }

        }
    }
}

With Substring the second parameter is the length of the substring. If you just want getCity to return 'L' you could change it to:

    return employeename.Substring(20,1).Trim();

Substring() method accepts two things one is character position and length from that position. In your code GetName() returns starting from zero position to 19th position and in 2nd method ie GetCity() returns from 19th position to rest of character in that string. So substring(19,2) will work I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM