格式化字符串
静态Format方法
Public static string Format(string format,object obj);
format:用来指定字符串所要的格式
obj:要被格式化的对象
(此处不是很懂)
format参数由零或多个索引占位符混合组成,其中索引占位符称为格式项,它们与此方法的参数列表中的对象相对应。格式设置过程将每个格式项替换为相应对象值的文本表示形式,格式项的语法是**{索引[,对齐方式][;格式字符串]}**,它指定了一个强制索引、格式化文本的可选长度和对其方式,以及格式说明符字符的可选字符串,其中格式说明符字符用于控制如何设置相应对象的值的格式。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string StrA = "呦吼吼吼";
string StrB = "啦啦啦啦";
string newstr = String.Format("{0},{1}~~~", StrA, StrB);
Console.WriteLine(newstr);
}
}
}
呦吼吼吼,啦啦啦啦~~~
截取字符串
Substring 方法可以截取字符串中指定位置和指定长度的子字符串
语法格式:
public string Substring(int startIndex,int length)
(字符串的起始位置的索引,字符串中的字符数)
如果length参数的长度大于截取字符串的长度,将从起始位置的索引处截取之后的所有字符
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string StrA = "呦吼吼吼吼吼";
string StrB = "";
StrB = StrA.Substring(1, 4);
Console.WriteLine(StrB);
}
}
}
分割字符串
string类提供了一个Split方法,用于分割字符串,此方法的返回值是包含所有分割子字符串的数组对象,可以通过数组取得所有分割的子字符串
语法格式:
public string[] split(params char[] separator);
separator 是一个数组,包含分隔符
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string StrA = "呦~吼吼!吼吼#吼";
char[] separator = { '~', '!', '#' };//声明分隔符的数组
String[] splitstrings = new string[100];//声明一个字符串数组
splitstrings = StrA.Split(separator);//分割字符串
for(int i = 0; i < splitstrings.Length; i++)
{
Console.WriteLine("item{0}:{1}", i, splitstrings[i]);
}
}
}
}
插入字符串
Insert方法,向字符串的任意位置插入新元素
public string Insert(int startIndex,string value); (用于指定插入的位置,0开始,指定插入的字符串)
填充字符串
PadLeft/PadRight 方法用于填充字符串,左侧/右侧填充
public string PadLeft(int totalWidth,char paddingChar) (指定填充后的字符串长度,所指定要填充的字符没省略则填充空格)
删除字符串
Public String Remove(int startIndex,[int count]);(开始删除的位置,删除的字符数量(此处没有则删除到最后一个字符为止))
复制字符串
copy方法
public static string Copy(string str) (要复制的字符串)
CopyTo方法 可以将字符串的某一部分复制到另一个数组
Public void CopyTo(int sourceIndex,char[]destination,int destinationIdex,int count);
(需要复制字符的起始位置,目标字符数组,指定目标数组中的开始存放位置,指定要复制的字符个数)
替换字符串
public string Replace(char Ochar,char Nchar) (代替换的字符,替换后的新字符)
public string Replace(string OValue,string NValue)(待替换的字符串,替换后的新字符串)