c# 怎么替换指定字符后的几位?
见下面的代码:
using System;
class Program
{
static void Main(string[] args)
{
string s = "hjshfkjhkhaE12461564";
//替换为空串,相当于删除
string result = Replace(s, string.Empty);
Console.WriteLine(result);
//替换为HAHA...
string result2 = Replace(s, "HAHA...");
Console.WriteLine(result2);
}
// 将字符串中'E'后连续3个字符,替换为newString
static string Replace(string src, string newString)
{
int index = src.IndexOf('E');
string s1 = src.Substring(0, index + 1);
string s2 = src.Substring(index + 4);
return s1 + newString + s2;
}
}
运行结果:
private void button1_Click(object sender,EventArgs e)
{
string s="hjshfkjhkhaE12461564";
int i=s.IndexOf("E");
string str=s.Substring(i+1,3);
s=s.Replace(str,"替换成你的字符串"); //若为"",就是替换为空
MessageBox.Show(s);
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int flag = 0;
string x = "dddfefwE12315";//test字符串
string y = string.Empty;//新字符串
for (int i = 0; i < x.Length; i++)//每个字符串的都可以使个Char数组
{
if (x[i] == 'E')//获得E的下标
{
flag = i;
}
if (i > flag && i <= flag + 3)//替换E下标后面三位的字符,,这里替换成x
{
y += "x";
}
else//替换范围以外的不变
{
y += x[i].ToString();
}
}
textBox1.Text = y;//输入新字符串。。
}
}
结果