Android에서 문자열의 각 문자 발생 횟수 계산하기
이 튜토리얼에서는 Android 앱에서 사용자가 입력한 문자열 내 각 문자가 몇 번 등장하는지 계산하여 화면에 표시하는 방법을 단계별로 알아봅니다. 핵심 원리는 HashMap을 활용해 각 문자를 키(key)로, 등장 횟수를 값(value)으로 저장하는 것입니다.
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"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:hint = "Enter Name"
android:layout_height = "wrap_content" />
<LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
<TextView
android:id = "@+id/textview"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>위 레이아웃은 세 가지 요소로 구성되어 있습니다. 사용자가 이름을 입력할 수 있는 EditText, 클릭 이벤트를 처리할 Button, 그리고 계산 결과를 출력할 TextView입니다. 사용자가 버튼을 클릭하면 입력된 문자열에서 각 문자의 등장 횟수를 확인한 뒤 그 결과를 TextView에 표시합니다.
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
EditText name;
HashMap<Character,Integer> charCountMap;
TextView textview;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
textview = findViewById(R.id.textview);
charCountMap = new HashMap<>();
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
char[] strArray = name.getText().toString().toCharArray();
for(char charItem:strArray) {
if(charCountMap.containsKey(charItem)) {
charCountMap.put(charItem,charCountMap.get(charItem)+1);
} else {
charCountMap.put(charItem,1);
}
}
textview.setText(charCountMap.toString());
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
name.setError("Enter NAME");
}
}
});
}
}코드 동작 방식:
- 버튼이 클릭되면 먼저 EditText가 비어 있는지 검사합니다. 비어 있다면
setError()를 통해 사용자에게 이름 입력을 요청합니다. - 입력값이 있으면
toCharArray()메서드로 문자열을 문자 배열(char 배열)로 변환합니다. - 배열을 순회하면서 HashMap에 해당 문자가 이미 존재하는지
containsKey()로 확인합니다. - 문자가 이미 있으면 기존 값에 1을 더해 저장하고, 없으면 값을 1로 하여 새로 저장합니다.
- 마지막으로 HashMap 전체를
toString()으로 변환해 TextView에 출력하고, Toast 메시지로 완료 여부를 알려줍니다.
애플리케이션 실행하기
이제 앱을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 나타납니다.

위 실행 결과에서 볼 수 있듯이, 버튼을 누르면 입력한 문자열에 포함된 각 문자의 등장 횟수가 TextView에 정상적으로 표시됩니다. 이처럼 HashMap 하나만으로도 반복문과 함께 간단하게 문자 빈도수를 집계할 수 있습니다.