यह प्रश्न पहले से ही अन्य सदस्यों द्वारा पूछा गया है/उत्तर दिया गया है लेकिन मेरा मामला थोड़ा अलग है ..स्ट्रिंग में शब्दों को कैसे उलटें?
समस्या: स्ट्रिंग में शब्दों को कैसे उलटें? आप strpos(), strlen(), substr() का उपयोग कर सकते हैं लेकिन अन्य बहुत उपयोगी कार्यों जैसे विस्फोट(), strrev() आदि
यह मूल रूप से एक साक्षात्कार प्रश्न है इसलिए मुझे तारों को कुशल बनाने की क्षमता प्रदर्शित करने की आवश्यकता है ।
उदाहरण:
$ स्ट्रिंग = "मैं एक लड़का हूँ"
उत्तर:
"मैं एमए एक yob"
नीचे मेरी समाधान है कि मुझे 2 दिन का समय लगा है (उच्छ्वास) लेकिन वहां अधिक सुरुचिपूर्ण समाधान होना चाहिए। मेरा कोड बहुत लंबा दिखता है ..
अग्रिम धन्यवाद!
मेरे इरादे:
1. get number of word
2. based on number of word count, grab each word and store into array
3. loop through array and output each word in reverse order
कोड:
<?php
$str = "I am a boy";
echo reverse_word($str) . "\n";
function reverse_word($input) {
//first find how many words in the string based on whitespace
$num_ws = 0;
$p = 0;
while(strpos($input, " ", $p) !== false) {
$num_ws ++;
$p = strpos($input, ' ', $p) + 1;
}
echo "num ws is $num_ws\n";
//now start grabbing word and store into array
$p = 0;
for($i=0; $i<$num_ws + 1; $i++) {
$ws_index = strpos($input, " ", $p);
//if no more ws, grab the rest
if($ws_index === false) {
$word = substr($input, $p);
}
else {
$length = $ws_index - $p;
$word = substr($input, $p, $length);
}
$result[] = $word;
$p = $ws_index + 1; //move onto first char of next word
}
print_r($result);
//append reversed words
$str = '';
for($i=0; $i<count($result); $i++) {
$str .= reverse($result[$i]) . " ";
}
return $str;
}
function reverse($str) {
$a = 0;
$b = strlen($str)-1;
while($a < $b) {
swap($str, $a, $b);
$a ++;
$b --;
}
return $str;
}
function swap(&$str, $i1, $i2) {
$tmp = $str[$i1];
$str[$i1] = $str[$i2];
$str[$i2] = $tmp;
}
?>
हमें पूछ आप के लिए एक साक्षात्कार सवाल का जवाब देने? :( –
एफडब्ल्यूआईडब्ल्यू, कोड मुझे ठीक दिखता है। –
@ इयान पी: उसने पहले ही इसका उत्तर दिया। वह पूछ रहा है कि ऐसा करने का एक और शानदार तरीका है। – webbiedave