Hi guys, how can i count, how many times the SpaceBar is pressed while writing the string:
With this code, it sais that:
`cool’ conflicts with a declaration in a child block
If you assume words are delimited by the “space” character, it’d be almost exactly what I already posted, except that you wouldn’t want to subtract 1 from the result. So:
string source = "This is my source string";
int wordCount = source.Split(' ').Length;
// The important part is the string split, a more verbose way of representing it would be this:
string toSplit = "This is an example string.";
string[] split = toSplit.Split(' ');
foreach(string str in split){
Debug.Log(str);
}
// This would output:
// "This"
// "is"
// "an"
// "example"
// "string."
// So the length of this "split" array is 5. To get the count of the spaces, he subtracted one
// To get the "word" count, just don't subtract that one
int wordCount = source.Split(' ').Length;
// This *may* not always be accurate though, depending on where your spaces are. A better way to handle it would be something like
int wordCount = 0;
foreach(string str in source.Split(' ')){
if (string.isNullOrEmpty(str.Trim()) == false){
wordCount++;
}
}
// This way it only counts actual strings containing at least one non-space character
// Otherwise something like " This is an example string. "; may return incorrect results
Ok, but if I would to count how many word like" source" are there in the string… I can’t use myString.split(‘source’); … so what have I to use in this case?