[java] 안드로이드 스플릿 스트링

나는이라는 문자열을 가지고 있으며 CurrentString이와 같은 형태입니다
"Fruit: they taste good".
를 구분 기호로 CurrentString사용하여 분할하고 싶습니다 :.
그렇게하면 단어 "Fruit"가 자체 문자열로 분리되어 "they taste good"다른 문자열이됩니다.
그런 다음 단순히 SetText()2 개의 다른 TextViews문자열 을 사용 하여 해당 문자열을 표시하고 싶습니다 .

이것에 접근하는 가장 좋은 방법은 무엇입니까?



답변

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

두 번째 문자열의 공백을 제거 할 수 있습니다.

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

점 (.)과 같은 특수 문자로 문자열을 분할하려면 점 앞에 이스케이프 문자 \를 사용해야합니다.

예:

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"

다른 방법이 있습니다. 예를 들어 StringTokenizer클래스를 (에서 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


답변

.split 메서드는 작동하지만 정규식을 사용합니다. 이 예에서는 (Cristian을 훔치기 위해) 다음과 같습니다.

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

또한
Android Split이 올바르게 작동하지 않습니다.


답변

쉼표로 안드로이드 분할 문자열

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


답변

     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();


답변

Android 전용 TextUtils.split () 을 고려할 수도 있습니다. 메서드 .

TextUtils.split ()과 String.split ()의 차이점은 TextUtils.split ()에 설명되어 있습니다.

분할 할 문자열이 비어 있으면 String.split ()은 [ ”]를 반환합니다. 이것은 []를 반환합니다. 결과에서 빈 문자열은 제거되지 않습니다.

나는 이것이 더 자연스러운 행동이라고 생각합니다. 본질적으로 TextUtils.split ()은 String.split ()의 얇은 래퍼이며 빈 문자열을 구체적으로 처리합니다. 이 방법의 코드 는 실제로 매우 간단합니다.


답변

문자열 s = “String =”

String [] str = s.split ( “=”); // 현재 str [0]은 “hello”이고 str [1]은 “goodmorning, 2,1″입니다.

이 문자열을 추가


답변