Stringa Android Split


227

Ho una stringa chiamata CurrentStringe ha la forma di qualcosa del genere "Fruit: they taste good".
Vorrei dividere l' CurrentStringutilizzo del :come delimitatore.
In questo modo la parola "Fruit"verrà divisa nella sua stringa e "they taste good"sarà un'altra stringa.
E poi vorrei semplicemente usare SetText()2 diversi TextViewsper visualizzare quella stringa.

Quale sarebbe il modo migliore per affrontare questo?


Probabilmente potresti provare a leggere in espressioni regolari. Funzionano anche bene.
— Shouvik,

10
@Falmarri - Qualsiasi domanda unica sulla programmazione è benvenuta su Stack Overflow.
— Tim Post

Risposte:


606
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Potresti voler rimuovere lo spazio per la seconda stringa:

separated[1] = separated[1].trim();

Se vuoi dividere la stringa con un carattere speciale come punto (.) Devi usare il carattere di escape \ prima del punto

Esempio:

String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"

Ci sono altri modi per farlo. Ad esempio, puoi usare la StringTokenizerclasse (da java.util):

StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method

Grazie per questo! Utile anche per separare ora e minuti durante la creazione di un nuovo oggetto Time.
— funzionato il

24
Grazie! Il metodo .split () non funziona affatto in Android! StringTokenizer funziona bene.
— Ayush Pateria

Sì, lo fa ... che problemi hai avuto?
— Cristian,

split in android riceve un'espressione regolare invece di un semplice divisore di stringhe.
— htafoya,

1
@HardikParmar usa i etPhoneNo.getText().toString().replaceAll("\\D", "");suoi dice che sostituisce tutto ciò che non è cifra
— MilapTank

86

Il metodo .split funzionerà, ma utilizza espressioni regolari. In questo esempio sarebbe (rubare a Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Inoltre, questo proviene da: Android split non funziona correttamente


52

stringa divisa android per virgola

String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
    System.out.println("item = " + item);
}

25
     String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
     StringTokenizer st = new StringTokenizer(s, "|");
        String community = st.nextToken();
        String helpDesk = st.nextToken(); 
        String localEmbassy = st.nextToken();
        String referenceDesk = st.nextToken();
        String siteNews = st.nextToken();

22

Potresti anche considerare il metodo specifico TextUtils.split () per Android .

La differenza tra TextUtils.split () e String.split () è documentata con TextUtils.split ():

String.split () restituisce [''] quando la stringa da dividere è vuota. Questo restituisce []. Ciò non rimuove alcuna stringa vuota dal risultato.

Trovo che questo sia un comportamento più naturale. In sostanza, TextUtils.split () è solo un wrapper sottile per String.split (), che si occupa in modo specifico del caso della stringa vuota. Il codice per il metodo è in realtà abbastanza semplice.


Qual è il vantaggio di usare TextUtils.split () invece di chiamare split () direttamente sulla stringa?
— nibario,

Risposta modificata per chiarire la differenza tra TextUtils.split () e String.split ()
— gardarh,

Grazie, in realtà ho letto la documentazione per TextUtils.split () ma per qualche motivo ho perso questo dettaglio. Immagino che ero stanco di capire cosa dicesse effettivamente.
— nibario,

0

String s = "String ="

String [] str = s.split ("="); // ora str [0] è "ciao" e str [1] è "buongiorno, 2,1"

aggiungi questa stringa

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.