Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
what is equivalent C# method for the javascript method 'charAt'?
Posted
Updated 16-Nov-11 0:50am
v2
Comments
Sergey Alexandrovich Kryukov 16-Nov-11 7:22am    
What part of Internet banned you? Google? MSDN? Too bad...
--SA
maajanes 16-Nov-11 7:44am    
I have to count the number of occurances of a particular character. What can i do?

I think you mean
C#
string alphabet = "abcdefg...xyz" ;
char b = alphabet[1] ;
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 16-Nov-11 7:21am    
OK, this is the only correct answer so far, my 5.
--SA
Sergey Alexandrovich Kryukov 16-Nov-11 7:26am    
I only added a post with trivial explanation, hope not quite useless, please see. :-)
--SA
Always read MSDN before (and typically, instead of) asking such questions: http://msdn.microsoft.com/en-us/library/system.string.aspx[^].

Asking such question at CodeProject is very ineffective compared to reading MSDN help pages, which you should do in all cases anyway.

—SA
 
Share this answer
 
In answer to your second question, namely
maajanes wrote:

I have to count the number of occurances of a particular character. What can i do?


The fastest pattern I have come across0 is
C#
string source = "this is my test string";
char requiredCharacter = 's';
int count = 0;
foreach (char c in source)
{
   if (c == requiredCharacter)
   {
       count++;
   }
}

0
Can't remember were the original came from as it was a while ago, but it is what I use now
 
Share this answer
 
You can do this using Substring() function of the String.

Suppose-
string sname="abcdef...yz";
int nCharAt=0;
char scharAt=Convert.ToChar(sname.Substring(nCharAt,1));

Then the answer will be as-
sCharAt=a;
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 16-Nov-11 7:21am    
It is by far not equivalent, by several reasons. Correct answer is done by Reiss: this is accessing a character by index using "[int]". One important thing to remember: strings are immutable. Substring operator creates brand new string in the heap (in C#, VB.NET) and initialize it by copying fragment of data. Accessing a character is much faster then that and does not have any memory overhead.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900