- Home /
Javascript Strings. check for number of strings in strings?
i was wondering how to see how many times a string contains a set of characers. though there might be easy way to do it with javascript. here is what i came up with. it works but it seems silly to say all this.
var checkarray:String[];
var words:String;
words="boring fun boring fun boring boring boring";
checkarray = words.Split("fun"[0]);
print("my user had fun " +checkarray.Length-1+" many times");
Also wondering about the String.Contains function. is there any way to get the character position when using String.Contains? or the characters following the spot without splitting?
Javascript here.
In Split the Character in the inverted commas is the separator for the split to occur.
If I am not mistaken your output will be
checkarray[0] = "boring "
checkarray[1] = " boring "
checkarray[2] = " boring boring boring".
If it works, roll with it, however I will say that the actual content of the array becomes completely arbitrary after you've taken the count, so you may as well nullify it/clear it.
Remember that working with strings is always slow.
oh, i noticed the word "slow" in your comment. arrgggg. the strings im parcing in my current project actually create over a thousand arrays.
my game has a seperate level editor that saves to the players hard drive in txt format. it also sends level strings to other online players thought the internet. it works fine for a one time start up. i was debating on weather to use string info during gameplay or pack info into arrays. these sort of questions dont get much responce here. ive been only scripting about a year now so i got a lot to learn. any opinions would be helpfull.
Answer by tigertrussell · Mar 06, 2015 at 05:57 PM
Are you familiar with Regular Expressions?
You could create a Regular Expression which would match the word "boring," then you use Javascript's RegEx functionality to count the number of matches within your string.
Thanks Tiger, I will surely check into it! im doing a lot with strings in my current project and trying to learn everything i can about them!
Unity "Javascript" isn't web Javascript so that won't work at all. Unity uses $$anonymous$$ono, hence the Regex class: https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v=vs.110).aspx
Your answer

Follow this Question
Related Questions
Get Component With Variable Help 2 Answers
NullRerenceException On comparisons 0 Answers
Using Buttons to write numbers 3 Answers
If String.Contains an item from List ? 1 Answer
Finding phrases within strings 2 Answers