Hi, how do I count characters in a string with C#?
Unity Answers is for Unity specific questions only.
Please ask language specific questions on a programming forum.
Also a 2 second Google search could have answered this question for you.
I did try google since that's the first thing I always do, and this is for unity 3D(thought I mentioned that, guess I left it out)
C# is not specific to Unity. It is C#.
Unity uses the MONO.NET framework which is almost identical to the Microsoft.NET framework.
Answer by XienDev
Oct 30, 2012 at 05:56 PM
May I ask how to implement it? Or an example please.
Kayden, I'd suggest doing this C# video course below, your questions are absolute basics of programming and it seems you are not ready to even ask questions on a forum.
Example: string value = "abcde"; int x = value.Length;
And, what Meltdown said. If you hope to make a game, you must learn to program.
wow... this thread was brutal... :)
Answer by Landern
Oct 30, 2012 at 06:53 PM
Your millage may vary and this can be done a lot of ways and Length is the right choice, but here you go.
public class SillyStringQuestion
private string sentence;
public SillyStringQuestion(string theString)
this.sentence = theString;
public int CountCharsTheString()
int result = 0;
charArray = sentence.ToCharArray();
foreach(char character in charArray)
throw new Exception("bummer no data and stuff");
Answer by firemyst
Apr 15, 2014 at 01:05 AM
For those that are interested, this website has benchmarked at least a dozen different ways to count the number of times a character occurs in a string, using both single threaded and multithreaded techniques.
Basically, the winner is either the single or parallel for-loop implementations as follows where "ss" is the Search String, "ch" is the array of characters you're looking for.:
for (int x = 0; x < ss.Length; x++)
for (int y = 0; y < ch.Length; y++)
for (int a = 0; a < ss[x].Length; a++ )
if (ss[x][a] == ch[y])
//it's a match. Do what you need to.
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
15 People are following this question.
What is the maximum byte length of Application.ExternalCall? (and oh yea, it doesn't escape strings correctly)
High Score Name entry
How to tell if a string contains some specified text
Enemy spawner help with lengths
Converting a String to Another Object's Boolean