「C#」文字列の文字をすべて置換するサンプル

2021年10月6日

書式
public string Replace (string oldValue, string? newValue);
現在のインスタンスに出現する指定した文字列をすべて、別に指定した文字列に置換した新しい文字列を返します。

oldValue String
置換される文字列。

newValue String
出現するすべての oldValue を置換する文字列。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oldStr = "study skill become smart study and exercise";
Console.WriteLine("置換前文字列:{0}'{1}'{0}", Environment.NewLine, oldStr);
// Replaceで文字列を置換
string newStr = oldStr.Replace("study", "STUDY");
Console.WriteLine("置換後文字列:{0}'{1}'",
Environment.NewLine, newStr);
Console.ReadKey();
}
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string oldStr = "study skill become smart study and exercise"; Console.WriteLine("置換前文字列:{0}'{1}'{0}", Environment.NewLine, oldStr); // Replaceで文字列を置換 string newStr = oldStr.Replace("study", "STUDY"); Console.WriteLine("置換後文字列:{0}'{1}'", Environment.NewLine, newStr); Console.ReadKey(); } } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string oldStr = "study skill become smart study and exercise";

            Console.WriteLine("置換前文字列:{0}'{1}'{0}", Environment.NewLine, oldStr);

            // Replaceで文字列を置換
            string newStr = oldStr.Replace("study", "STUDY");

            Console.WriteLine("置換後文字列:{0}'{1}'",
                    Environment.NewLine, newStr);

            Console.ReadKey(); 
        }
    }
}

実行結果
置換前文字列:
'study skill become smart study and exercise’

置換後文字列:
'STUDY skill become smart STUDY and exercise’

C#

Posted by arkgame