Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding words to a sentence!

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Hi, I'm a beginner and I have a problem.
I have this variable which contains (usually/hopefully) a sentence. I would like to add random words to different places in the sentence. To be more specific, I would like to add a random word [FOO, BAR or COOL] after the fourth, seventh and tenth word of the sentence..
For example:

Sentence:
Tek-Tips is the hot web community where computer professionals meet and talk.

Result:
Tek-Tips is the hot BAR web community where COOL computer professionals meet FOO and talk.

If the sentence was longer, the random word would be placed with intervals of three (actually everywhere in the sentence except in the beginning, where it is placed after the fourth word).
I hope I'm understood.

So, how can this be achieved?? I'm a newbie so I would appreciate an example.
 
seems like I answered this same question a day or two ago...... seems like maybe there is an assignment due sometime soon???? ;^)

Check out splice. An example can be found in the post in this forum called
Inserting Array Values .... a day or two back...

'hope this helps....




keep the rudder amid ship and beware the odd typo
 
Yeah, it helps.
But what is the fastest way? Could it be done with just one splice?
 
I don't see how. You could set up a function that cycled through the splices for you, instead of doing the long hand. But, the splice syntax does not appear to handle more than one splice at a time.

# I think this should work.
Code:
# hash of {word to add, new position for word}
%spliceThese = ('word1','2','word2','4','word3','6');
@string = ('a','string','of','words','to','be','played','with','for','fun');

foreach $newWord (keys(%spliceThese))
    {
    $position = '';
    $position = $spliceThese{$newWord};
    splice @string,$position,0,$newWord;
    }

'hope this helps.





keep the rudder amid ship and beware the odd typo
 
I've got another one:

Code:
$sentence = "I wrote this text to test my fancy word adding function.";  
@words = split(" ",$sentence);
srand;
for ($n = 3; $n < scalar(@words)-1; $n += 3)
 {
	@adds = (' FOO',' BAR', ' MOO');	
	$words[$n] .= $adds[int rand(@adds)];
 }
$it = join(&quot; &quot;,@words);
print $it;

In this one, you don't have to know the size of the sentence. After all, TMTOWTDI, right?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top