代码之家  ›  专栏  ›  技术社区  ›  Christopher Pisz

数组偏移到结束[重复]

c#
  •  1
  • Christopher Pisz  · 技术社区  · 6 年前

    在C++中,我可以使用指针算法从开始位置到数组的末尾抓取所有东西。为了完成同样的任务,你做了什么?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static string GetText(byte[] value, uint startPos)
            {
                // TODO - What goes here?
                return "";
            }
    
            static void Main(string[] args)
            {
                byte[] value = new byte[] { 0x41, 0x42, 0x42, 0x42 };
                string result = GetText(value, 1);
                Console.WriteLine(result);
            }
        }
    }
    

    预期输出:

    2 回复  |  直到 6 年前
        1
  •  5
  •   Attersson    6 年前
    string result =System.Text.Encoding.UTF8.GetString(value);
    return result.Substring(startPos,result.Length-startPos);
    

    (检查startPos是否在0和length-1范围内)

    或与 GetString

    return System.Text.Encoding.UTF8.GetString(value, startPos, startPos-value.Length);
    
        2
  •  0
  •   Rui Fernandes    6 年前

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static string GetText(byte[] value, int startPos)
            {
                if(startPos >= 0 && startPos <= value.Length)
                {
                   return System.Text.Encoding.UTF8.GetString(value).Substring(startPos);
                }
                else
                {
                   return string.Empty;
                }
            }
    
            static void Main(string[] args)
            {
                byte[] value = new byte[] { 0x41, 0x42, 0x42, 0x42 };
                string result = GetText(value, 1);
                Console.WriteLine(result);
            }
        }
    }