- Home /
How to count the number of strings in a string class?
How do you count the number of strings used in the same string class? Said for example I have two scripts.
in script one//
public void something(string someWord) {
//the number of string that belongs to someWord. in this case is 3.
//How do I do it in C#?
}
And in script two//
void addstuff() {
script one.something("word a");
script one.something("word b");
script one.something("word c");
}
P.S. (in case you still don't understand me) I have looked for a solution but so far is only dealing with how many letters in a string. However, I want the number of words (or string)that has been created by the script or a another script calling it.
by number of strings do you mean by number of words seperated by space or number of letters in the string? or is it completly different.
I'm not a c# expert but as far as I know there's no such method to count words in ".net". It shouldn't be too hard to build one. Just get the string variable you want and check each time it detects a space in that string variable. That number + 1 should theorically represent the quantity of words.
while it's overkill for this use case, there is RegEx (regular expression lib)
Answer by GenuiTix · Feb 21, 2014 at 07:58 AM
If you are going to store and use those strings later, you should use list to do that. For using list directly you have to declare preprocessor instruction
using System.Collection.Generic;
at the beginning of your code. Nærby simillar declariations. Later in your code you have to declare list in body of yours class. Like that:
List <string> stringsStored;
Your function is rædy now to cøllect string list:
public void something(string someWord) {
stringsStored.Add(someWord);
// Below is your code
}
Than the strings amount will be accessible through
stringsStored.Count
from all other functions in this class. Ås your function is public it will be accessible from other modules as well (until your class is public).
Or
Something simpler. You can use counter defined outside 'something' function bødy and increment it every time the function has been invoked.
int counter = 0;
public void something(string someWord) {
counter++;
//Other stuff
}
I thought I included complete solution for the list. I'll update my post then.
Thanks, I have used you second solution scene that how the assessment is (partially) written up.
Answer by whydoidoit · Feb 21, 2014 at 08:47 AM
Presuming you have a string:
var numberOfWords = someString.Split( new [] { ' ', '\t' }).Length;
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# String Array Has Missing or Incorrect Keycode Strings 2 Answers
Can I create a list with an int/float and a string? C# 2 Answers