Omar Alaa Omar Alaa - 21 days ago 4
C# Question

C# Type of String Index

I need to access a very large number in the index of the string which

int
and
long
can't handle. I had to use
ulong
but the problem is that the indexer can only handle the type
int
.

This is my code and I have marked the line where the error is located. Any ideas how to solve this?

string s = Console.ReadLine();
long n = Convert.ToInt64(Console.ReadLine());
var cont = s.Count(x => x == 'a');
Console.WriteLine(cont);
Console.ReadKey();


The main idea of the code is to identify how many
'a'
s there are in the string. What are some other ways I can do this?

EDIT:

i didn't know that is the string index Capicity cant exceed the int type. and i fixed my for loop by replacing it with this linq line

var cont = s.Count(x => x == 'a');


now since my string can't exceed certain amount. so how i can repeat my string to append its char for 1,000,000,000,000 times rather than using this code

for (int i = 0; i < 20; i++)
{
s += s;
}


since this code is generating random char numbers in the string and if i raised the 20 may cause to overflow so i need to adjust it to repeat itself to make the string[index] = n // the long i declared above.
so for example if my string input is "aba" and n is 10 so the string will be "abaabaabaa" // total chars 10

PS: I Edited the original code

Answer

I highly recommend you rethink the way you are doing this, but a quick fix would be to use a foreach loop instead:

foreach(char c in s)
{
    if (c == 'a')
        cont++;         
}

Alternative using Linq:

cont = s.Count(c => c == 'a');

I'm not sure about what n is supposed to do. According to your code it limits the string length but your question never mentions why or to what end.

Comments