If you're tempted to think something bad, the first thing you should consider is picking up and moving yourself someplace a little more spiritually open. However, when flight is not an option (like in math class), start humming a church hymn to yourself. If you are in math class, please hum softly. Thank you.
If you hymn/whistle/sing/think about words to a hymn, it's hard for temptation to stay there. I mean, imagine that you're Satan, and you're stuffing rude thoughts into little Bob's head, when all of a sudden, you hear Come, come ye saints...No toil nor labor fear. That's like Satan's eviction notice, right there.
Other good strategies for keeping your thoughts clean include concentrating on something else, looking away completely, talking to a close friend, or thinking about pictures of Christ.
The problem is, once you start actually entertaining those thoughts, you know you're headed for something un-good. Jeffrey R. Holland said that, "Like thieves in the night, unwelcome thoughts can and do seek entrance to our minds. But we don’t have to throw open the door, serve them tea and crumpets, and then tell
them where the silverware is kept!"(April 2010 General Conference). If bad thoughts come, tell them to skeedaddle! Ha, I used an old folks word. But really, sometimes you need to say, "Skeedaddle!" I've done it before, and the funniness just gets rid of the bad thoughts.
If you really wanna go hard-core with keeping clean thoughts, just follow the simple "primary answers". Read scriptures. Say prayers. Go to bed and wake up in a healthy way (Ugh, Shane, are you crazy?). Go to seminary. If you don't know what that is, may I refer you to lds.org, the official website of the church.
Above all, keep your mind preoccupied with good thoughts. It's hard for Satan to tempt you if you're right in the middle of reliving the funny joke about the elders' quorum you heard the other day.