1

In C++ I could use pointer arithmetic to grab everything from a start position to the end of an array. What do you do in C# to accomplish the same thing?

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);
        }
    }
}

Expecting output: BBB

Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65
  • You would never get "BBB" in c++. You would get "ABBB". – jdweng Aug 16 '18 at 16:54
  • `.Length` - 1 will give you the last indexed value in an array. So if you are trying to convert bytes to characters and append it to a string, you could use a `for loop` starting at uint startPos and loop until `value.Length - 1` – Ryan Wilson Aug 16 '18 at 16:55
  • @jdweng he wants to skip the characters until index is startPos, in this case 1, skipping the A – clcto Aug 16 '18 at 16:55
  • Do you expect the 1 to refer to a byte offset, or a character offset? They may very well be different. – Jon Skeet Aug 16 '18 at 17:03
  • In general, you might want to become familiar with LINQ, which has methods like `Skip` and `ToArray()` and `ToList()`. In this case : `value.Skip(startPos)` would return an enumerable of bytes from `startPos` to the end, then you would use standard byte-to-text conversion. – BurnsBA Aug 16 '18 at 17:59

2 Answers2

5
string result =System.Text.Encoding.UTF8.GetString(value);
return result.Substring(startPos,result.Length-startPos);

(check that startPos is within 0 and length-1)

Or with GetString

return System.Text.Encoding.UTF8.GetString(value, startPos, startPos-value.Length);
Attersson
  • 4,755
  • 1
  • 15
  • 29
0

I believe that you can achieve what you need with

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);
        }
    }
}
Rui Fernandes
  • 270
  • 1
  • 11