简体   繁体   English

C#分割字符串

[英]C# Split the string

I want to know how to split the string into different lengths or chunks. 我想知道如何将字符串分成不同的长度或块。 Eg I want the name to be split into 0 to 19 with 0 the starting position and 19 the ending position. 例如,我希望将名称分为0到19,起始位置为0,结束位置为19。 Any ideas on how I could do this? 关于如何执行此操作的任何想法?

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("Tom");
            Console.WriteLine(i.getString());
            Console.ReadLine();
        }

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

            public employee(string name)
            {
                this.employeename = name;
            }

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

You probably want to do as below, since strings are immutable in C#. 您可能要执行以下操作,因为字符串在C#中是不可变的。 When you do like you had, the "effect" is lost because you are not assigning that result to anything. 当您按原样进行操作时,“效果”将丢失,因为您没有将结果分配给任何对象。

return employeename.Substring(0, 19).Trim();

Also note you lose original string once you assign "Tom" to it, through the constructor. 还要注意,一旦通过构造函数将“ Tom”分配给原始字符串,就会丢失原始字符串。

PS. PS。 When you pass start position and length which go out of bounds of the string instance you will get an exception. 当您传递超出字符串实例范围的起始位置和长度时,您将获得异常。

As i understand, you want to split on comma separator, you have two options: 据我了解,您想拆分逗号分隔符,您有两个选择:

Option 01: 选项01:

  public string getString()
  {
      return employeename.Substring(0, employeename.IndexOf(',').Trim();
  }

Option 02: 选项02:

    public string getString()
    {
        return employeename.Split(',').FirstOrDefault();
    }

Happy to Help you! 很高兴为您服务!

following to what Giorgi said, change the implementation: 遵循Giorgi所说的,更改实现:

      public string getString()
        {
            if (employeename.Length > 19)
            {
                 return employeename.Substring(0, 19).Trim();
            }
            else
            {
                  //return error OR
                  return employeename;
            }

        }

also, your string is too short when assigning "tom" to it, you must make sure that you have atleast 19 characters.. i don't have VS in front of me, but basiclly the above implementation is better 另外,给它分配“ tom”时,字符串太短,必须确保至少有19个字符。.我前面没有VS,但是基本上上述实现更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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