2016-04-21 15 views
5
public void BubbleSortArrayString(string[] letters) //change here 
{ 
    bool swap; 
    string temp; //change this too 

    do 
    { 
     swap = false; 

     for (int index = 0; index < (letters.Length - 1); index++) 
     { 
      if (letters[index] > letters[index + 1]) //if first number is greater then second then swap 
      { 
       //swap 

       temp = letters[index]; 
       letters[index] = letters[index + 1]; 
       letters[index + 1] = temp; 
       swap = true; 
      } 
     } 

    } while (swap == true); 
} 

Sono riuscito a creare una sorta di decimale a bolla, ma io sono un suck con una stringa, ho un file di testo con mesi e ho bisogno di ordinarlo in ordine alfabetico. Ho ricevuto l'errore:Come mettere in bolla l'ordinamento di un array di stringhe?

operator > cannot be applied to type string and string

L'aiuto sarebbe apprezzato.

+1

FYI: 'true' == non è necessaria in quanto si tratta solo di valutare se il valore booleano è uguale a un altro valore booleano per restituire un valore booleano, dal momento che già avere un valore booleano per iniziare puoi semplicemente usarlo ('while (swap)') – Sayse

risposta

5

È possibile utilizzare string.Compare(x,y) al posto di <, che restituisce 0 se la stringa sono uguali, altrimenti un numero intero che indica la loro posizione relativa nella ordinamento

for (int index = 0; index < (letters.Length - 1); index++) 
    { 
     if (string.Compare (letters[index], letters[index + 1]) < 0) //if first number is greater then second then swap 
     { 
      //swap 

      temp = letters[index]; 
      letters[index] = letters[index + 1]; 
      letters[index + 1] = temp; 
      swap = true; 
     } 
    } 

Se si desidera ignorare caso durante il confronto, dovresti utilizzare string.Compare (letters[index], letters[index + 1], true)

+0

Grazie mille! – georgeThornton96

0

È possibile utilizzare String.CompareOrdinal per le stringhe. Inoltre, sarebbe meglio se si inverte l'istruzione if per ridurre il raggruppamento. Come questo:

if (String.CompareOrdinal(letters[index], letters[index + 1]) >= 0) continue;      
temp = letters[index]; 
letters[index] = letters[index + 1]; 
letters[index + 1] = temp; 
swap = true; 

Da MSDN:

This method performs a case-sensitive comparison using ordinal sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. To perform a case-insensitive comparison using ordinal sort rules, call the Compare(String, String, StringComparison) method with the comparisonType argument set to StringComparison.OrdinalIgnoreCase.