1.string与字符串变量stringbuilder
* 1.少量字符串操作,且字符串不经常发生变化时,优先使用stirng
* 2.stringbuilder创建后大小是可以发生变化,但是string大小是不可变的
* 3.stringbuilder可以自动扩容,且2倍扩容
namespace Program
{
class Program
{
static void Main(string[] args)
{
string s1 = "abc";
string s2 = "hello world";
//比较字符串
Console.WriteLine(String.Compare(s1, s2));
//查找包含
Console.WriteLine(s1.Contains("wo"));
Console.WriteLine(s2.Substring(5));
Console.WriteLine(s1 + s2);
string[] s3 = { "hello", "world","c#" };
Console.WriteLine(String.Join(s1,s3));
StringBuilder sb = new StringBuilder();
//字符串变量容量
sb.Capacity = 64;
Console.WriteLine("容量为:" + sb.Capacity);
Console.WriteLine("长度为:" + sb.Length);
sb.Append("abc");
//将abc加到字符串变量sb的后边
Console.WriteLine("容量为:" + sb.Capacity);
Console.WriteLine("长度为:" + sb.Length);
sb.Append("hello world");
Console.WriteLine("容量为:" + sb.Capacity);
Console.WriteLine("长度为:" + sb.Length);
Console.WriteLine("sb:" + sb);
sb.Append("hello2 world2");
Console.WriteLine("容量为:" + sb.Capacity);
Console.WriteLine("长度为:" + sb.Length);
Console.WriteLine("sb:" + sb);
sb.Append(false);
Console.WriteLine("sb:" + sb);
//在第五个位置插入
sb.Insert(5, 123);
Console.WriteLine("sb:" + sb);
}
}
}
2.字符串写入文件
//将字符串sr写入文件中
public void WriteToFile(string str)
{
//双引号为txt文件路径 不允许有中文
FileStream fs = new FileStream("d:\\message.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(str);
//刷新
sw.Flush();
sw.Close();
fs.Close();
}