Utilisation de compareToIgnoreCase () pour comparer une entrée à une sous-chaîne dans une chaîne sans utiliser de tableau

Nov 21 2020

Dans ma mission, il est interdit d'utiliser des collections et des tableaux. Nous sommes autorisés à utiliser String Tokenizer, mais toutes les autres classes que String et System ne sont pas autorisées. Cette solution doit fonctionner avec n'importe quel nombre d'entrées.

J'ai une chaîne qui ressemble à ceci:

1|Aaron|Peter|3063543030|[email protected] + "\n" 
2|Buffet|Anthony|3063543030|[email protected] + "\n" 
3|Dunty|Richard|3063543030|[email protected] 

Par exemple, si l'entrée est 4|Doe|John|3063543030|[email protected] alors la comparaison sera effectuée en utilisant compareToIgnoreCase () et l'entrée sera insérée juste avant 3 | Dunty | Richard | 3063543030 | john @ gmail. com

Ici, j'ai une méthode qui obtient le nom de l'entrée et utilise String Tokenizer:

 public static String obtenirNomContact (String contactLigne) {
        StringTokenizer tokenizer = new StringTokenizer(contactLigne, "|");
        String id = tokenizer.nextToken();
        String nom = tokenizer.nextToken();
        String prenom = tokenizer.nextToken();


        return nom;
    }

Dans cette méthode, j'insère l'entrée dans la chaîne et fais la comparaison en utilisant compareToIgnoreCaseMethod ()

 public static String insertEntryInString
        (String myString, String entry) {
            int result = 0;
            String entryName = "";
            String myString = "";
            String entry = "";
            String nameInString = "";
    
            if (myString != null) {
                myString += entry + "\n";
    
                do {
                    entryName = getContactName(entry);
                    nameInString = getContactName(myString);
    
                    result = entryName.compareToIgnoreCase(nameInString);
                    if (result < 0) {
    
                        entry += entryName + "\n";
                        entry += nameInString + "\n";
                    } else {
                        entry += nameInString  + "\n";
                        entry += entryName + "\n";
                    }
    
                } while (result > 0);
                myString += entry + "\n";
                System.out.println(myString);
            }
          
            return myString;  
        }

Ce que j'essaye de faire sans succès pour l'instant, c'est d'insérer l'entrée dans la chaîne uniquement si le résultat de la comparaison est égal à 1 ou 0.

J'apprécierais si quelqu'un pouvait m'aider à résoudre ce problème.

Merci

Réponses

1 AlexRudenko Nov 21 2020 at 23:33

Supposons que les méthodes d'assistance suivantes soient implémentées pour obtenir le nom et le nom du contact:

static String getSurname(String contact) {
    StringTokenizer st = new StringTokenizer(contact, "|");
    st.nextToken(); // skip id
    return st.nextToken();
}

static String getName(String contact) {
    StringTokenizer st = new StringTokenizer(contact, "|");
    st.nextToken(); // skip id
    st.nextToken(); // skip surname
    return st.nextToken();
}

Ensuite, la méthode pour insérer un nouveau contact dans une "liste" triée de contacts séparés par '\n'peut être réécrite comme suit:

private static final String NL = "\n";

static String insertContact(String contact, String data) {
    String newSurname = getSurname(contact);
    String newName = getName(contact);
    
    StringTokenizer st = new StringTokenizer(data, NL);
    StringBuilder sb = new StringBuilder();
    boolean inserted = false;
    
    while (st.hasMoreTokens()) {
        String curr = st.nextToken();
        String currSurname = getSurname(curr);
        String currName = getName(curr);
        
        if (!inserted && (currSurname.compareToIgnoreCase(newSurname) > 0 || (currSurname.compareToIgnoreCase(newSurname) == 0 && currName.compareToIgnoreCase(newName) > 0))) {
            inserted = true;
            System.out.println("Inserting before " + curr);

            sb.append(sb.length() > 0 ? NL : "").append(contact);
        }
        sb.append(sb.length() > 0 ? NL : "").append(curr);
    }
    if (!inserted) {
        sb.append(sb.length() > 0 ? NL : "").append(contact);
    }
    System.out.println("Data:\n" + sb);
    System.out.println("---------");
    return sb.toString();
}

Tester:

String data = "1|Abercrombie|Peter|3063543030|[email protected]\n" 
            + "2|Buffet|Anthony|3063543030|[email protected]\n" 
            + "3|Dunty|Richard|3063543030|[email protected]";

data = insertContact("4|Doe|John|3063543030|[email protected]", data);
data = insertContact("5|Aaron|Paul|5551234567|[email protected]", data);
data = insertContact("6|Gilligan|Vince|5559123456|[email protected]", data);

Production:

Inserting before 3|Dunty|Richard|3063543030|[email protected]
Data:
1|Abercrombie|Peter|3063543030|[email protected]
2|Buffet|Anthony|3063543030|[email protected]
4|Doe|John|3063543030|[email protected]
3|Dunty|Richard|3063543030|[email protected]
---------
Inserting before 1|Abercrombie|Peter|3063543030|[email protected]
Data:
5|Aaron|Paul|5551234567|[email protected]
1|Abercrombie|Peter|3063543030|[email protected]
2|Buffet|Anthony|3063543030|[email protected]
4|Doe|John|3063543030|[email protected]
3|Dunty|Richard|3063543030|[email protected]
---------
Data:
5|Aaron|Paul|5551234567|[email protected]
1|Abercrombie|Peter|3063543030|[email protected]
2|Buffet|Anthony|3063543030|[email protected]
4|Doe|John|3063543030|[email protected]
3|Dunty|Richard|3063543030|[email protected]
6|Gilligan|Vince|5559123456|[email protected]
---------