您的位置:首页 > 其它

B5第五章第1节String常用方法1

2015-07-06 14:50 253 查看
第五章第1节
bool Contains(String str):判断字符串对象是否包含给定的字符串。
bool StartsWith(String str):判断字符串对象是否以给定的字符串开始。

bool EndsWith(String str):判断字符串对象是否以给定的字符串结束。

/*string s1 = "Hello";
Console.WriteLine(s1.Contains("el"));
Console.WriteLine(s1.Contains("abc"));
*/
/*
Console.WriteLine(s1.StartsWith("He"));
Console.WriteLine(s1.StartsWith("he"));
*/

/*
string s = "http://www.rupeng.com";
if (s.StartsWith("https://") &&
(s.EndsWith(".com") || s.EndsWith(".cn")))
{
Console.WriteLine("合法网址");
}
else
{
Console.WriteLine("非法网址");
}*/
/*
string email = "3333@173.com";
string username = "毛东东万岁";
if (email.EndsWith("@qq.com"))
{
Console.WriteLine("本站不支持QQ邮箱");
Console.ReadKey();
return;
}
if (username.Contains("毛东东") || username.Contains("总书记"))
{
Console.WriteLine("用户名请勿使用敏感词汇");
Console.ReadKey();
return;
}*/

B5第五章第2节String常用方法2

第五章第2节
int Length:获取字符串的长度属性

char ch = s[3];

int IndexOf(int ch):返回指定字符在此字符串中第一次出现的索引

int IndexOf(String str):返回指定字符串在此字符串中第一次出现的索引

LastIndexOf:最后一次出现的位置。

String Substring(int start):截取字符串。返回从指定位置开始截取后的字符串。

String Substring(int start,int length)截取字符串。返回从指定位置开始截取指定长度length的字符串。

string s1 = "hellooabcdaabe";
int i = s1.IndexOf('l');
Console.WriteLine(i);
Console.WriteLine(s1.IndexOf("ab"));
Console.WriteLine(s1.LastIndexOf('l'));

string s2 = s1.Substring(4);
Console.WriteLine(s2);
Console.WriteLine(s1.Substring(4,3));
案例获取一个文件名的名称和扩展名部分:

string filename = "[ADS-118]林志aaaaaa玲.avi";//
int dotIndex = filename.IndexOf('.');//3
string name = filename.Substring(0, dotIndex);
Console.WriteLine(name);
string ext = filename.Substring(dotIndex + 1);
Console.WriteLine(ext);

练习:从http://www.rupeng.com:8090/a.htm获得域名、端口号

解:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 第五章第2节获得域名_端口号
{
class Program
{
static void Main(string[] args)
{
//获得域名
string s1 = "http://www.rupeng.com:8090/a.htm";
int i = s1.IndexOf('.');
int j = s1.LastIndexOf(':');
String s2 = s1.Substring(i+1,j-i-1);
Console.WriteLine(s2);
//获得端口号
int k = s1.LastIndexOf('/');
String s3 = s1.Substring(j+1,k-j-1);
Console.WriteLine(s3);
Console.ReadKey();
}
}
}

第五章第2节联系题B5第五章第2节联系题获取ads--118

string filename = "[ADS-118]林志玲.mp3";
int i = filename.IndexOf('[');
int j = filename.IndexOf(']');
string k = filename.Substring(i + 1, j - i - 1);
Console.WriteLine(k);
Console.ReadKey();
//输出ASD-118

B5第五章第3节String常用方法3

第五章第3节
1、String ToLower():把字符串变成小写;String ToUpper():把字符串变成大写

2、String Replace(char oldChar,char newChar):用新的字符去替换指定的旧字符;
string s1="Hello";
console.writeline(s1.Replace('l','L'));
3、Replace(String oldStr,String newStr):用新的字符串去替换指定的旧字符串

string s2="rupeng is a niubi ";
string s3=s2.Replace("rupeng","如鹏王");

4、String trim():去除字符串两端空格, Trim(params char[] trimChars)去掉两端的给定字符。 TrimEnd()去掉末尾空格、 TrimStart()去掉开头空格。
【【
string s1=" acb d ";
console.writeline("名字是【"+s1.Trim()+"】");
//String trim():去除字符串两端空格,

console.writeline("名字是【"+s1.TrimEnd()+"】");
//去掉字符串末尾空格

console.writeline(",名字是【"+s1.Replace(" ","")+"】");
//用replace实现把头尾、中间的空格都去掉

string s2="--abc_d??__-"
console.writeline(s2.Trim('-','_','?'));
//Trim(params char[] trimChars)去掉两端的给定字符。
】】

5、String是不可变的,因此上面的操作都是生成新的字符串对象,要用返回值去取新的字符串。

6、String[] Split(...):重载方法很多,字符串按照分隔符切割。案例:把字符串用“,”分割

案例:给一个全班数学考试成绩的字符串“50, 80,33,58,99, 82”,成绩用逗号分隔,有的成绩中可能有空格,有的地方逗号是英文、有的逗号是中文。统计班级的平均分。

B5第五章第4节Directory类

第五章第·4节
CreateDirectory(string path):创建文件夹全路径

void Delete(string path, bool recursive):删除文件夹path, recursive表示是否也删除子文件及子文件夹。如果文件夹不为空, recursive=false,则抛异常;

bool Exists(string path):判断文件夹是否存在

EnumerateFiles、 EnumerateDirectories遍历文件和文件夹;

// Directory.CreateDirectory(@"d:\temp\a\b\c");
//Directory.Delete(@"d:\temp\");//目录=文件夹,只能删除空文件夹
//Directory.Delete(@"D:\temp\redissessiontest", true); //递归删除

IEnumerable<string> files1 =
//Directory.EnumerateFiles(@"d:\temp");
//Directory.EnumerateFiles(@"d:\temp","*.*",SearchOption.AllDirectories);
Directory.EnumerateFiles(@"d:\temp", "*.avi", SearchOption.AllDirectories);
IEnumerator<string> filesEnum1 = files1.GetEnumerator();
while (filesEnum1.MoveNext())//在结果中向下移动一条
{
Console.WriteLine(filesEnum1.Current);//获得当前结果
}

B5第五章第4节String常用方法4

第五章4节
1、bool IsNullOrEmpty(string value):判断字符串是否为null或者是空字符串;
string s1=null;//s没有指向任何字符串对象
string s2="";//空字符串
if(string.IsNullOrEmpty(s))
//if(s==null || s.length<=0)
//if(s==null || s=="")
{
console.writeline("不能为空");
}

2、bool Equals(string a, string b, StringComparison. OrdinalIgnoreCase):不区分大小写比较。案例:验证码
String s1="abc";
String s2="AbC";
Console.WriteLine(s1==s2);
Console.WriteLine(string.Equals(s1,s2,StringComparison.OrdinalIgnoreCase));
Console.WriteLine(s1.ToLower()==s2.ToLower());

3、string Join(string separator, params string[] value)把一个数组(集合)用分隔符separator连接为一个字符串。

string[] strs={"如鹏","百度","新浪"};
string s1=string.Join("%%%%",strs);
console.writeline(s1);

int[] nums={3,5,6,7,32};
string s2=string.Join("|",nums);

B5第五章第8节 StringBuilder

第五章第8节
1、使用反编译发现

String s7="111"+"222"+"333"+"444"+"555"

会被优化为 String s7 = "111222333444555";

但是String s6 = s1 + s2 + s3 + s4 + s5;就没那么幸运了,每次+都会生成一个String对象,当连接字符串比较多的时候就会产生临时字符串对象。

2、使用StringBuilder拼接字符串则不会有临时字符串对象的问题:

StringBuilder sb = new StringBuilder();

sb.Append(s1);

sb.Append(s2);

sb.Append(s3);

因为Append方法把this返回了,还可以sb.Append(s1).Append(s2).Append(s3);

最后使用String s = sb.ToString()一次性生成拼接结果字符串即可

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonClassTest2
{
class Program
{
static void Main(string[] args)
{
/*
string s1 = "aaa" +
+"aaaaa"+"bbb";
Console.WriteLine(s1);
*/
string s1 = "aaa";
string s2 = "bbb";
string s3 = "ccc";
string s4 = "ddd";
string s5 = "afadsf";
string s6 = s1 + s2 + s3 + s4 + s5;

StringBuilder sb = new StringBuilder();
/*
sb.Append(s1);
sb.Append(s2);
sb.Append(s3);
sb.Append(s4);
sb.Append(s5);
sb.Append(33);*/
sb.Append(s1).Append(s2).Append(s3).Append(s4).Append(s5);
sb.AppendLine("hello");
sb.AppendLine("afasdfads");

string s7 = sb.ToString();
Console.WriteLine(s7);

Person p1 = new Person();
p1.Eat().Sleep().Dota();//链式编程 Jquery
Console.ReadKey();
}
}

class Person
{
public Person Eat()
{
Console.WriteLine("吃饭");
return this;
}
public Person Sleep()
{
Console.WriteLine("睡觉");
return this;
}
public Person Dota()
{
Console.WriteLine("打Dota");
return this;
}
}
}

B5第五章第9节可空的int(值类型)

第五章第9节
1、int等是值类型,不能为null。有时想表达“不知道数字是多少”的时候,用int任何值表示都不 合适。

2、C#中可以用“int?”表示“可空的int”。注意类型转换:

int? i1=5;

if(i1!=null)

{

int i= (int)i1;

}

3、也可以通过i1.HasValue判断是否为null、i1.Value来获得值。

int? i = null;
int? i2 = 3;
if (i == null)
{
Console.WriteLine("i为null");
}
if (i2 != null)//i2.HasValue
{
//i2++;
i2 = i2 + 3;
//int i3 = i2;//把可能为null的int?赋值给
//一定不为null的int
int i3 = (int)i2;//i2.Value
Console.WriteLine(i2);
}
long? l = null;
string? str=null;//不可以这样使用

B5第五章第10节案例:LED时钟

第五章第10节
1、.Net使用DateTime类表示时间数据类型。DateTime属于结构体,因此也是值类型。

2、DateTime.Now当前时间;DateTime.Today当前日期。

3、可以通过Year、Month、Hour 等属性得到日期的年、月、小时等部分;也可以用构造函数根据给定的时间创建一个对象。

DateTime dt = DateTime.Now;
Console.WriteLine(dt);
Console.WriteLine(DateTime.Today);

DateTime dt2 = new DateTime(2019, 9, 10);
Console.WriteLine(dt2);

Console.WriteLine(dt.Year);
Console.WriteLine(dt.DayOfYear);
Console.WriteLine(dt.Second);

B5第五章第11节异常的概念和捕获

第五章第11节
1、异常的根类为Exception。异常类一般都继承自Exception

2、

try

{

String s = null;

s.ToString();

}

catch (NullReferenceException ex)

{

Console.WriteLine("为空"+ex.Message);

}

e就是发生异常的异常类对象,变量名只要不冲突就任意。

3、在异常处理中,一旦try里面有问题了。放弃try代码块中之后的代码,直接跳到catch里面执行。如果try代码后还有代码,则处理完catch后还会继续执行。

4、多个异常的处理

try
{
int a = 10;
int b = 0;
Console.WriteLine(a / b);
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[3]);
}
catch (DivideByZeroException ae)
{
Console.WriteLine("除数不能为0");
}
catch (IndexOutOfRangeException ae)
{
Console.WriteLine("数组越界异常");
}
可以catch住父类异常,这样就可以抓住所有子类异常了,但是强烈不建议大家这样做,特别是不要没理由的catch(Exception ex)

5、好的异常处理习惯:

不要只是把异常catch住什么都不做或者只是打印一下,这不是正常的“异常处理”。

不知道怎么处理就不要catch,出错比“把错误藏起爱”好。这样以为“不会出错了”,其实是把异常“吃掉了”,会让程序陷入逻辑混乱状态,要科学合理的处理异常(以后经常用就明白了)。

B5第五章第12节 tryfinally

第五章第12节
try{
//有可能有问题代码
}catch(异常类型 异常变量){
//处理方式
}finally{
//无论“有可能有问题代码”是否出错都要执行的代码
}

B5第五章第13节 File类

第五章第13节
File是静态类(无法被new)中的主要静态方法:

void Delete(string path):删除文件;

bool Exists(string path):判断文件是否存在;

string[] ReadAllLines(string path):将文本文件中的内容读取到string数组中;

string ReadAllText(string path):将文本文件读取为一个字符串

void WriteAllLines(string path, string[] contents):将string[]写入到文件中;

void WriteAllText(string path, string contents):将字符串contents写入到文件path中。

AppendAllText:向文件中附加内容;Copy复制文件;Move移动文件

/*
if(File.Exists(@"d:\temp\a.pnproj"))
{
File.Delete(@"d:\temp\a.pnproj");
}*/

/*
string[] lines = File.ReadAllLines(@"d:\temp\my.txt",
Encoding.Default);
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine("第"+i+"行:"+lines[i]);
}*/
/*
String s = File.ReadAllText(@"d:\temp\my.txt");
Console.WriteLine(s);
*/
// File.WriteAllText(@"d:\temp\test.txt", "如鹏网欢迎你");
//File.AppendAllText(@"d:\temp\test.txt", "afasfsafadsf");

B5第五章第15节FileStream写入

第五章第15节

FileStream fs = new FileStream(@"d:\temp\1.txt",FileMode.Create);
byte[] bytes1 = Encoding.Default.GetBytes("如鹏网你好\r\n");
//任何数据都是以byte为单位写入的。GetBytes获得字符串的byte表示形式
fs.Write(bytes1,0,bytes1.Length);

byte[] bytes2 = Encoding.Default.GetBytes("www.rupeng.com");
fs.Write(bytes2,0,bytes2.Length);//在上一个Write的结尾继续写入
fs.Close();//一定要用完了关闭
Stream写入的单位是byte(字节),char转换为byte时候,一个英文char转换为一个byte(对应的ASCII码),一个中文char转换为两个byte(*采用GBK编码时),试着输出bytes的长度。

采用Default、UTF8、UTF32得到的字符串的byte[]长度不一样,因此说明不同类型编码在计算机中存储的不一样。用什么编码写入就用什么编码读取,否则会有乱码的问题。

不要往C盘写,因为Win7、Win8默认普通程序没有权限读写C盘。

B5第五章第17节using简化资源释放

第五章第17节
定义一个实现了IDisposable接口的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOTest2
{
class MyFileStream:IDisposable
{
public MyFileStream()
{
//throw new Exception("初始化出错");
}

public void Write(int i)
{
throw new Exception("Write出错");
Console.WriteLine("写入了"+i);
}

public void Dispose()
{
Console.WriteLine("Dispose被调用了,开始释放资源,虽然没什么可释放的");
}
}
}

使用:

using (MyFileStream fs1 = new MyFileStream())
{
using (MyFileStream fs2 = new MyFileStream())
{
fs2.Write(333);
fs1.Write(5);
}
}

可以同时声明多个资源:

using (MyFile f1 = new MyFile())

using (MyFile f2 = new MyFile())

{

}

using其实就是编译器简化的try……finally操作,通过ILSpy反编译成IL可以看出来。

using只是try……finally,如果需要catch,只要catch就是了。

B5第五章第19节FileSream实现文件的拷贝

第五章第19节
1、while((len=inStream.Read(bytes,0,bytes.Length))>0)把读取并且返回读取的长度给len,然后判断len的值综合为了一句话。复习:复制表达式的值就是赋值后的变量的值。
2、outStream.Write(byte,0,len);每次write都会从上次write的最后位置接着写入。将byte[]数组b写入outStream中,off代码距离当前写入位置的偏移量,一般写0,len代表写入多长。
缓冲区先设置为50,在修改为1M,体验速度的变化,使用Stopwatch类进行代码计时。。

B5第五章第21节StreamReader和StreamWrite

1、直接用Stream进行文本文件的读写会比较麻烦,因为要考虑文件的编码、中文字符等的问题。

2、StreamReader、StreamWriter是用来读写字符流(character stream)的类,会帮着自动处理麻烦的问题。

using (Stream outStream = new FileStream(@"d:\temp\1.txt", FileMode.Create))
using(StreamWriter sw = new StreamWriter(outStream,Encoding.Default))
{
sw.Write("你好a如鹏网");
sw.WriteLine("hehe");
sw.WriteLine("1111");
}
1
2
3
4
5

using (Stream inStream = new FileStream(@"d:\temp\1.txt", FileMode.Open))
using (StreamReader reader =new StreamReader(inStream, Encoding.Default))
{
/*
string s = reader.ReadToEnd();
Console.Write(s);*/
/*
string s1 = reader.ReadLine();
Console.WriteLine(s1);

string s2 = reader.ReadLine();
Console.WriteLine(s2);
*/
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}

B5第五章第22节泛型List

第五章第22节
1、数组长度是固定的,List<T>可以动态增删内容。List<T>是泛型的,可以在声明的时候指定放什么类型的数据。

List<int> list = new List<int>();

list.Add(1);

list.Add(2);

list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });

list.AddRange(list);//另一个list

2、如何遍历?

for (int i = 0; i < list1.Count; i++)

{

int num = list1[i];

Console.WriteLine(num);

}

3、int[] nums = list.ToArray(); //List泛型集合可以转换为数组

List<string> listStr = new List<string>();

string[] str = listStr.ToArray();

B5第五章第23节字典Dictionary

第五章第23节
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("zs", "张三");
dict.Add("ls", "李四");
dict.Add("ww", "王五");
dic["ls"] = "小赵";
String s = dict["ww"];
dict.ContainsKey();

//<k,v>k是键的类型(根据谁查),v是值的类型(查什么)
/*
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("abc", 123);//往字典中放数据(k,v)
dict.Add("aaa", 222);
int i = dict["abc"];//根据key从字典中查数据
Console.WriteLine(i);
Console.WriteLine(dict["aaa"]);*/

/*
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("zs","张三");
dict.Add("ls", "李四");
// dict.Add("ls","李斯");// 如果key已经存在,则抛异常
dict["ls"] = "李斯";//如果不存在key,则添加;如果存在则替换
dict["ww"] = "王五";

string name = dict["ls"];
Console.WriteLine(dict.ContainsKey("ls"));
Console.WriteLine(dict.ContainsKey("abc"));
Console.WriteLine(name);

第二十四节foreach
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: