C#ではSplit
というメソッドを使うことで簡単に文字列の分割ができます。
使い方は次のような感じです。
コンマ「,
」かハイフン「-
」で分割
using System;
class Example1
{
static public void Main()
{
string str = "one,two-three";
char[] sep = { ',', '-' };
string[] ar = str.Split(sep, StringSplitOptions.None);
foreach(string s in ar) {
Console.WriteLine(s);
}
}
}
実行結果
one
two
three
連続した3つのハイフン「---
」で分割
using System;
class Example2
{
static public void Main()
{
string str = "one---two-three";
string[] sep = { "---" };
string[] ar = str.Split(sep, StringSplitOptions.None);
foreach(string s in ar) {
Console.WriteLine(s);
}
}
}
実行結果
one
two-three
他に、正規表現を使って分割したりもできます。
リンク
String.Split Method (System) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.string.split
関連記事
C#のcharを大文字・小文字に変換する方法
C#のstringを大文字・小文字に変換したい場合はToLower/ToUpperが使えます。
string s;
// 小文字に変換
s.ToLower();
// 大文字に変換
s.ToUpper();
そこで、charを大文字・小文字に変換したい場合に何か簡単な方法がないか調べてみたところChar.ToLower/Char.ToUpperというのが便利みたいです。
使...
正規表現で文字列を分割したい場合はRegex.Split
C#で正規表現で文字列を分割したい場合はRegex.Splitが便利です。使い方は次のような感じです。
数字で分割するサンプル
using System;
using System.Text.RegularExpressions;
public class Example1
{
static public void Main ()
{
string pattern ...
C#の文字列補完
string.Formatを使うと、次のような感じで変数の値を文字列に変換して出力できます。
コード
string name = "abc";
int value = 123;
Debug.Log(string.Format("name={0}, value={1}", name, value));
出力
name=abc, value=123
便利でよく使っていた...