Okay, so the first thing is that I'm cheating a little bit there, since all I've done is just fixed your code. If you wanted to do proper pattern matching than you would need something like this:Cybernetic pig wrote:Wait, why this?
Wouldn't giving i the value of myName.length defeat the purpose of this lesson? I'm confused.Code: Select all
i = i + myName.length;
Also, in the if statement, within the parenthesis there is . Why is in square brackets and not:I gave it square brackets but I have no idea why, cannot remember, yet the code still works....Code: Select all
if (text (i)==="C"){ code code code; }
In my lessons so far I have only been taught one use of square brackets: to hold the parameters of an array.
Code: Select all
var randomtext = "asdfajfilCyberPahskjdfbaiusd";
var name = "CyberP";
var result = [];
for (i = 0; i < randomtext.length;i++) {
for (j = 0; j < name.length; j++) {
if (!(randomtext[i+j]=== name[j])) {
j = name.length; // Exits the loop if we get a mismatch
}
if (j===(name.length-1)) { // We looped through all of name successfully
result.push(name);
}
}
}
What the A[N] operator does is that is that is accesses Nth element of array A. And strings are arrays of characters (in some languages anyway).
Also, the reason I gave the value of name.length to i in the previous code is because I assumed that the pattern is not recursive. Basically what I was doing is that I loop (sometimes this is called to "iterate over", for reasons I won't go into) through all the characters in your source, and if one it finds matches the start of the name string it copies the next 'name.length' characters into the array of results, then skips ahead by N.
The first code I gave you does exactly that and works perfectly fine for your problem, in a way. The obvious issue is that it won't work if you have a mismatch after the first letter.