이 예제는 안드로이드(Android) TextView에서 split() 메서드를 활용해 문자열을 분리하는 방법을 단계별로 설명합니다.
구현 단계
1단계 − 새 프로젝트 생성
Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 필요한 모든 세부 정보를 입력합니다.
2단계 − 레이아웃 파일 작성
res/layout/activity_main.xml에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout>
위 레이아웃에는 이름을 입력받는 EditText, 클릭 버튼, 그리고 결과를 표시할 TextView가 배치되어 있습니다. 사용자가 버튼을 클릭하면 입력된 데이터를 가져와 공백 정규식(\\s)을 기준으로 문자열을 분리하게 됩니다.
3단계 − MainActivity 코드 작성
src/MainActivity.java에 다음 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
String[] replace = name.getText().toString().split("\\s");
text.setText(String.valueOf(replace[1]));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}핵심 로직은 split("\\s") 부분입니다. 이 정규식은 하나 이상의 공백 문자를 기준으로 입력 문자열을 나누며, 그중 인덱스 1번째 값(두 번째 단어)을 TextView에 출력합니다. 입력값이 비어 있으면 에러 메시지를 표시하도록 처리했습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 실행(Run) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

위 결과에서 입력란에 "Krishna sai sai"라는 문자열을 입력하고 버튼을 클릭하면, 문자열이 공백을 기준으로 분리되어 인덱스 1번째 값인 "sai"가 TextView에 출력되는 것을 확인할 수 있습니다.