Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying string to char array quickly

Tags:

string

c#

input

I need to read a string from standard input, perform some operations and meanwhile I need to copy some of input to char array. In C++ I could do it like this:

scanf("%s", &array[pos]);

which copies string s to char array at position pos. I need to do do this very quickly (olympic task). Reading from one big while in C++ took 5 sec. On C# I tried copying to array using string.elementAt() in a loop but it took 70 seconds, which is way too much. Also, building one big string and than using string.ToCharArray() is a bad idea. Any ideas how to do that?

char[] ciag = new char[1010001];
for(int x = 0 ; x < n ; x++){
line = Console.ReadLine();
sekw[x] = poz;
len = int.Parse(line.Split(' ')[0]);  //length of string to copy
string znaki = line.Split(' ')[1];    //copied string
for (int j = 0; j < len; j++)
{
ciag[poz + j] = znaki[j];  //put into array. Perhaps slow.
}
poz += len;
ciag[poz++] = 'k';  //my stuff
}
like image 895
rank1 Avatar asked Dec 17 '25 22:12

rank1


1 Answers

public void CopyTo(
    int sourceIndex,
    char[] destination,
    int destinationIndex,
    int count
)
like image 54
Feng Yuan Avatar answered Dec 19 '25 15:12

Feng Yuan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!