C#基础部分三(补充)

一、字符串

字符串替换:string Replace(string oldValue,string newValue)将字符串中出现oldValue的地方替换为newValue

取子字符串:string SubString(int startIndex),取从startIndex开始一直到最后的子字符串    string SubString(int startIndex,int length),取从位置startIndex开始长度为length的子字符串,如果子字符串的长度不足length则报错

bool Contains(string value)判断字符串中是否含有value

bool StartWith(string value)判断字符串是否以value开始

bool EndWith(string value)判断字符串是否以value结束

int IndexOf(string value)取value第一次出现的位置

例子:

static void Main(string[] args)
{
//Replace()通常用来替换敏感词
string s = "hallo,everyone!hallo!";
s = s.Replace("hallo","Hello");
Console.WriteLine(s);

//Substring()
string a = "http://www.baidu.com";
string 域名 = a.Substring(7); //从指定序号开始一直到最后的子字符串
Console.WriteLine(域名);

string a1 = a.Substring(7,5); //第二个参数指的是截取多长的字符串,代表长度(length)
Console.WriteLine(a1);

//如果参数超过了长度,会出现异常

//Contains()
string s1 = "我们的社会很和谐";
if (s1.Contains("社会") || s1.Contains("和谐"))
{
Console.WriteLine("含有敏感词汇");
}


//StartsWith()和EndWith()
string s2 = "http://www.blog.com";
if (s2.StartsWith("http://") || s2.StartsWith("https://"))
{
Console.WriteLine("是一个网址");
}
else
{
Console.WriteLine("不是网址!");
}

//IndexOf()
string s3 = "nihao,我是***";
int i = s3.IndexOf("我是"); //返回字符串第一次出现的位置
Console.WriteLine(i);

int j = s3.IndexOf("你是"); //如果没有,返回值是-1
Console.WriteLine(j);
Console.ReadKey();
}

 

二、函数的ref、out参数

ref必须先初始化,因为是引用,所以必须先有,才能引用,而out是内部给外部赋值,所以不需要初始化。 ref应用场景:内部对外部的值进行改变,out则是内部为外部变量赋值,out一般用在函数有多个返回值

namespace refout参数
{
class Program
{
static void Main(string[] args)
{
int i1 = 10;
int i2 = 20;
Swap(ref i1, ref i2);
Console.WriteLine("i1={0},i2={1}",i1,i2);
Console.ReadKey();
}
static void Swap(ref int i1, ref int i2)
{
int temp = i1;
i1 = i2;
i2 = temp;
}
}


int.TryParse 使用out获取两个返回值:

            string str = Console.ReadLine();
int i;
if (int.TryParse(str, out i))
{
Console.WriteLine("转换成功!{0}", i);
}
else
{
Console.WriteLine("数据错误!");
}
Console.ReadKey();


-----------------------------------今天完成了第一季视频,只算是把C#一些基础的东西看了。准备把问题也整理上来,嗯,加油!-----------------------------------------

posted @ 2012-01-27 19:11  王小萌  阅读(276)  评论(2编辑  收藏  举报