2010-06-04 16 views
8

Questa domanda è già stata posta/risposta dagli altri membri, ma il mio caso è un po 'diverso ..Come invertire le parole in una stringa?

Problema: come invertire le parole in una stringa? Puoi usare strpos(), strlen(), substr() ma non altre funzioni molto utili come explode(), strrev() ecc.

Questa è fondamentalmente una domanda di intervista quindi devo dimostrare di saper manipolare le stringhe .

Esempio:

$ string = "Sono un ragazzo"

Risposta:

"I ma un ragazzaccio"

Qui di seguito è la mia soluzione che mi ha portato 2 giorni (sigh) ma deve esserci una soluzione più elegante. Il mio codice sembra molto lungo ..

Grazie in anticipo!

La mia intenzione:

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 

Codice:

<?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; 
} 

?> 
+3

ci chiede di rispondere a una questione intervista per voi? :( –

+0

FWIW, il codice mi sembra a posto. –

+1

@Ian P: Ha già risposto, sta chiedendo se c'è un modo più elegante per farlo. – webbiedave

risposta

17
$string = "I am a boy"; 

$reversed = ""; 
$tmp = ""; 
for($i = 0; $i < strlen($string); $i++) { 
    if($string[$i] == " ") { 
     $reversed .= $tmp . " "; 
     $tmp = ""; 
     continue; 
    } 
    $tmp = $string[$i] . $tmp;  
} 
$reversed .= $tmp; 

print $reversed . PHP_EOL; 
>> I ma a yob 
-1

http://php.net/strrev

Edit: Avete chiesto per ogni parola per essere invertita, ma ancora in ordine "parola". Qualcosa di simile potrebbe funzionare meglio:

$string = "I am a boy!"; 
$array = explode(" ", $string); 
foreach ($array as &$word) { 
    $word = strrev($word); 
} 
$rev_string = implode(" ", $array); 
+1

La sua domanda non lo permette! –

+0

Sì, l'ho visto dopo aver risposto :) –

+0

Ha vinto 's anche la risposta corretta. Vuole invertire ogni parola individualmente. – webbiedave

2

Ops! Mis-read la domanda. Qui si va (Si noti che questo si dividerà su tutti i confini non lettera, non solo lo spazio Se si desidera un personaggio da non dividere su, basta aggiungerlo al $wordChars.):

function revWords($string) { 
    //We need to find word boundries 
    $wordChars = 'abcdefghijklmnopqrstuvwxyz'; 
    $buffer = ''; 
    $return = ''; 
    $len = strlen($string); 
    $i = 0; 
    while ($i < $len) { 
     $chr = $string[$i]; 
     if (($chr & 0xC0) == 0xC0) { 
      //UTF8 Characer! 
      if (($chr & 0xF0) == 0xF0) { 
       //4 Byte Sequence 
       $chr .= substr($string, $i + 1, 3); 
       $i += 3; 
      } elseif (($chr & 0xE0) == 0xE0) { 
       //3 Byte Sequence 
       $chr .= substr($string, $i + 1, 2); 
       $i += 2; 
      } else { 
       //2 Byte Sequence 
       $i++; 
       $chr .= $string[$i]; 
      } 
     } 
     if (stripos($wordChars, $chr) !== false) { 
      $buffer = $chr . $buffer; 
     } else { 
      $return .= $buffer . $chr; 
      $buffer = ''; 
     } 
     $i++; 
    } 
    return $return . $buffer; 
} 

Edit: Ora è una funzione singola e memorizza il buffer in modo ingannevole in notazione invertita.

Edit2: ora gestisce i caratteri UTF8 (basta aggiungere caratteri "parola" alla stringa $wordChars) ...

+0

domanda non consente l'uso di strrev() – thetaiko

+0

@thetaiko Grazie, ho letto male la domanda inizialmente. Modificato in una soluzione ... – ircmaxell

+0

Buono per gestire UTF-8. Ho aggiunto anche una soluzione, ma con stringhe e numeri regolari. –

1

Credo che il modo più semplice sarebbe quella di inserire la stringa in un array utilizzando explode() e che usando la funzione array_reverse(). Ovviamente dovrai produrre l'array. Per maggiori dettagli su array_reverse() vedi http://php.net/manual/en/function.array-reverse.php

0

Si sarebbe potuto fare in un modo molto più elegante se PHP utilizzata la sintassi concatenativa :)

{ 
    "" "" 3 roll 
    { 
     dup " " == 
      { . . "" } 
      { swp . } 
     ifelse } 
    foreach . 
} "reverse" function 

"I am a boy" reverse echo // Prints "I ma a yob" 
0
$str = "Hello how are you"; 

$teststr = explode(" ",$str); 

for($i=count($teststr)-1;$i>=0;$i--){ 
echo $teststr[$i]." "; 
} 


Output : you are how hello 
+0

O/p dovrebbe essere olleh wou rea uoy .... hai fatto tutta la stringa come inverso – Affan

0
<?php 
    // Reversed string and Number 
    // For Example : 
     $str = "hello world. This is john duvey"; 
     $number = 123456789; 
     $newStr = strrev($str); 
     $newBum = strrev($number); 

     echo $newStr; 
     echo "<br />"; 
     echo $newBum; 

OUTPUT : 
first : yevud nhoj si sihT .dlrow olleh 
second: 987654321 
+1

Non gli è permesso usare strrev come menzionato in questione –

0

La mia risposta è quello di contare il lunghezza della stringa, dividere le lettere in una matrice e quindi, loop indietro. Questo è anche un buon modo per verificare se una parola è un palindromo. Questo può essere usato solo per stringhe e numeri regolari.

preg_split può essere modificato in explode().

/** 
* Code snippet to reverse a string (LM) 
*/ 

$words = array('one', 'only', 'apple', 'jobs'); 

foreach ($words as $d) { 
    $strlen = strlen($d); 
    $splits = preg_split('//', $d, -1, PREG_SPLIT_NO_EMPTY); 

    for ($i = $strlen; $i >= 0; $i=$i-1) { 
     @$reverse .= $splits[$i]; 
    } 

    echo "Regular: {$d}".PHP_EOL; 
    echo "Reverse: {$reverse}".PHP_EOL; 
    echo "-----".PHP_EOL; 
    unset($reverse); 
} 
Problemi correlati