Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android開発】StringBufferの使い方を徹底解説!文字列操作の基本メソッドまとめ

はじめに:StringBufferとは?

具体的なサンプルコードに入る前に、まず「StringBuffer(ストリングバッファ)」について簡単に確認しておきましょう。

StringBufferクラスは、変更可能(ミュータブル)な文字列を扱うためのクラスです。JavaではStringオブジェクトは不変(イミュータブル)であるため、文字列を頻繁に連結・編集する場合には、新しいオブジェクトが都度生成されてパフォーマンスが低下します。一方、StringBufferは既存の文字列を直接書き換えられるため効率的で、さらにスレッドセーフである点も大きな特徴です。マルチスレッド環境でも安全に文字列操作が行えます。

本記事では、AndroidアプリでEditTextに入力された文字列を取得し、StringBufferの各メソッドを使って操作した結果をTextViewに表示するサンプルを紹介します。

手順1:新規プロジェクトを作成する

Android Studioを起動し、「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。

手順2:レイアウトファイル(activity_main.xml)を作成する

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">
    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter string" />
    <Button
        android:id="@+id/click"
        android:layout_marginTop="50dp"
        style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
        android:layout_width="wrap_content"
        android:background="#c1c1c1"
        android:textColor="#FFF"
        android:layout_height="wrap_content"
        android:text="Button" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

このレイアウトには、文字列入力用のEditText、実行用のButton、そして結果表示用のTextViewが5つ配置されています。ボタンがクリックされると、EditTextから入力値を取得し、StringBufferの各メソッドで加工した結果がそれぞれのTextViewに表示される仕組みです。

手順3:MainActivity.javaに処理を実装する

src/MainActivity.java に以下のコードを記述します。

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText edit_query;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit_query = findViewById(R.id.edit_query);
        final TextView textView = findViewById(R.id.text);
        final TextView textView1 = findViewById(R.id.text1);
        final TextView textView2 = findViewById(R.id.text2);
        final TextView textView3 = findViewById(R.id.text3);
        final TextView textView4 = findViewById(R.id.text4);
        findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!edit_query.getText().toString().isEmpty()) {
                    StringBuffer stringBuffer = new StringBuffer(edit_query.getText().toString());
                    textView.setText(" default String : " + stringBuffer);
                    textView1.setText(stringBuffer.insert(0, "insert at 0 " + "tutorialspoint.com"));
                    textView2.setText("Capacity is " + stringBuffer.capacity());
                    textView3.setText("Delete : " + stringBuffer.delete(1, 3));
                    textView4.setText("append : " + stringBuffer.append(" appended to string buffer"));
                }
            }
        });
    }
}

コードのポイント解説

  • insert(0, 文字列):指定したインデックス位置(ここでは先頭の0番目)に文字列を挿入します。
  • capacity():現在確保されている内部バッファの容量を返します。
  • delete(開始位置, 終了位置):指定範囲の文字を削除します(終了位置は含まれません)。
  • append(文字列):既存の文字列の末尾に新しい文字列を連結します。

なお、ボタンクリック時には isEmpty() で入力チェックを行い、空文字の場合は処理しないようガードしています。

アプリを実行してみよう

それでは実際にアプリを起動してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提とします。Android Studioからプロジェクト内のアクティビティファイルを開き、ツールバーの実行(Run)アイコンをクリックします。デバイス選択画面で接続中のモバイル端末を選択すると、端末の画面に以下のような結果が表示されます。

【Android開発】StringBufferの使い方を徹底解説!文字列操作の基本メソッドまとめ

上記の実行結果では、EditTextに入力した元の文字列に対して、挿入(insert)、容量確認(capacity)、削除(delete)、連結(append)といった各種操作を適用した結果が、それぞれのTextViewに順番に表示されていることが確認できます。

まとめ

StringBufferを使えば、文字列の挿入・削除・連結などの操作を効率よく、かつスレッドセーフに行えます。頻繁に文字列を書き換える場面では、StringではなくStringBuffer(またはStringBuilder)の活用を検討してみてください。

  1. AndroidでStringBuilderクラスを使う方法を実例付きで解説

    具体的な例に入る前に、まずStringBuilderクラスの基本について確認しておきましょう。StringBuilderクラスは可変(ミュータブル)な文字列を生成するためのクラスです。スレッドセーフではないため、複数のスレッドから同時にアクセス可能という特徴があります。本記事では、AndroidアプリでStringBuilderクラスを実際に使う方法を、サンプルコードとともに段階的に解説します。StringBuilderの主な特徴文字列を自由に追加・挿入・削除・変更できる(可変)Stringと異なり、操作のたびに新しいオブジェクトを生成しないため高速スレッドセーフではない(同期が必要な場合はS

  2. 【Android】ButterKnifeの使い方をサンプルコード付きで徹底解説!

    この記事では、Androidアプリ開発で定番だったアノテーションライブラリ「ButterKnife」の使い方を、実際にサンプルプロジェクトを動かしながらステップごとに解説します。 ButterKnifeとは? ButterKnifeは、Jake Wharton氏が開発したAndroid向けのビューインジェクションライブラリです。従来のようにfindViewById()でビューを1つずつ取得する代わりに、@BindViewアノテーションをフィールドに付けるだけで、対応するビューが自動的に注入されます。ボイラープレートコードが減り、Activityのコードがすっきりと読みやすくなるのが大きなメリ