気軽に遊べるミニゲームを制作しています

ブラウザゲームまとめ

【c# WPF道場】テキスト(文字列)の使い方

WPF

フォームの作成

まずはテキストボックスとボタンを1つずつ配置します。

テキストボックスの名前を Text1に変更しておきます。

指定の文字列で終わっているか調べる

テキストボックスの文字列が指定の文字列で終わっていれば①の処理を行うといったときに便利です。

ファイルのパスを取得して、そのファイルがpdf, xlsxであった場合、任意の処理を行う。といったときに使います。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfTextApp
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Text1.Text.EndsWith(".pdf"))
            {
                MessageBox.Show("このファイルはpdfです");
            }
            else
            {
                MessageBox.Show("このファイルはpdfではありません");
            }
        }

    }
}

動作確認1.テキストボックスの文字列が.pdfで終わっていた場合

動作確認2.テキストボックスの文字列が.pdfで終わっていなかった場合

文字列をキーワードで分割して、別配列に格納する

テキストボックスの文字列をあるキーワードで分割して扱うときに使用します。例えば、” ,” などが含まれた文字列を切り離して扱う場合に使います。

ボタン関数の処理を下記のように変更します。
切り離した2番目の文字列をメッセージボックスに表示します。

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string textString = Text1.Text;
            string[] splitString = textString.Split(',');
            MessageBox.Show(splitString[1]);
        }

動作確認:,以降の2番目の文字列がメッセージボックスに表示されています。

文字列を後ろから削除する

Remove関数を使って、取得した文字列の後ろから削除する場合に使います。

ボタン関数を以下のように変更します。

       private void Button_Click(object sender, RoutedEventArgs e)
        {
            string textString = Text1.Text;
            string removeString = textString.Remove(textString.Length - 2);
            MessageBox.Show(removeString);
        }

後ろ2文字の”ox”が削除されました。

文字列から指定位置の文字を削除する

Remove関数を使って、指定位置の文字を削除します。以下、2つの方法があります。

①文字列.Remove(削除開始位置) //開始位置までの文字は残る
②文字列.Remove(削除開始位置, 削除したい文字数)

コードを下記のように変更します。

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string textString = Text1.Text;
            string removeString1 = textString.Remove(3);
            string removeString2 = textString.Remove(2,4);
            MessageBox.Show(removeString1);
            MessageBox.Show(removeString2);
        }

①の場合、3文字目までの文字列を残し、残りを削除します。

②の場合、2文字目まで残り、そこから4文字(move)の部分が削除されます。

指定した文字列が存在するか確認する

Contains関数を使って、文字列に指定の文字列が存在するか確認できます。

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string textString = Text1.Text;
            if (textString.Contains(",") == true)
            {
                MessageBox.Show("この文字列は,を含んでいます。");
            }
        }

コメント

タイトルとURLをコピーしました