이 예제는 안드로이드(Android)에서 TextView에 표시된 텍스트의 단어 수를 계산하여 출력하는 방법을 소개합니다. 메모 앱이나 독서 앱처럼 글자 수·단어 수 통계 기능이 필요할 때 유용하게 활용할 수 있으니, 차근차근 따라 해 보세요.
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:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>
위 코드에서는 문단을 보여줄 TextView 하나를 화면 가운데에 배치했습니다. 이 TextView에 담긴 텍스트의 단어 수를 토스트(Toast)를 통해 화면에 표시하게 됩니다.
3단계: 메인 액티비티 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.");
String[] para = text.getText().toString().split("\\s+");
Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
}
}핵심 로직 살펴보기
단어 수를 계산하는 핵심은 다음 한 줄입니다.
String[] para = text.getText().toString().split("\\s+");split() 메서드에 정규식 \s+를 넣으면 스페이스, 탭, 줄바꿈 같은 공백 문자가 하나 이상 연속되는 지점을 기준으로 문자열을 분리합니다. 분리된 배열의 length 값이 곧 단어 수이며, 이 값을 Toast.makeText()로 감싸 화면 하단에 잠시 표시합니다.
참고로 텍스트 앞뒤에 불필요한 공백이 있으면 빈 요소가 생겨 개수가 어긋날 수 있으므로, trim()을 먼저 호출해 주면 더 정확한 결과를 얻을 수 있습니다.
String[] para = text.getText().toString().trim().split("\\s+");애플리케이션 실행
이제 앱을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같이 기본 화면이 표시됩니다.
