IndexOf()、Substring()用法

   int V = (pr.ToString().IndexOf("."));
    if (V != -1)
                {
                    pr = int.Parse(pr.ToString().Substring(0, V));
                }

取整:

doule i=100.11; 
int index = i.IndexOf("."); 
string Z= i.ToString().Substring(0,index)); 
string L= i.ToString().Substring(index + 1);
Z就是所要得到的整数

IndexOf() 
查找字串中指定字符或字串首次出现的位置,返首索引值,如: 
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置) 
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置) 
str1.IndexOf("字",start,end);//从str1第start+1个字符起,查找end个字符,查找“字”在字符串STR1中的位置[从第一个字符算起]注意:start+end不能大于str1的长度


indexof参数为string,在字符串中寻找参数字符串第一次出现的位置并返回该位置。如string s="0123dfdfdf";int i=s.indexof("df");这时i==4。 
如果需要更强大的字符串解析功能应该用Regex类,使用正则表达式对字符串进行匹配。


indexof() :在字符串中从前向后定位字符和字符串;所有的返回值都是指在字符串的绝对位置,如为空则为- 1

string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";

test.indexof(’d’) =2 //从前向后 定位 d 第一次出现的位置
test.indexof(’d’,1) =2 //从前向后 定位 d 从第三个字符串 第一次出现的位置
test.indexof(’d’,5,2) =6 //从前向后 定位 d 从第5 位开始查,查2位,即 从第5位到第7位;

lastindexof() :在字符串中从后向前定位字符和字符串;、
用法和 indexof() 完全相同。


下面介绍 IndexOfAny ||lastindexofany

他们接受字符数组做为变元,其他方法同上,返回数组中任何一个字符最早出现的下标位置

如下

char[] bbv={’s’,’c’,’b’};
string abc = "acsdfgdfgchacscdsad";

Response.Write(abc.IndexOfAny(bbv))=1
Response.Write(abc.IndexOfAny(bbv, 5))=9
Response.Write(abc.IndexOfAny(bbv, 5, 3))=9

lastindexofany 同上。

 String.SubString(int   index,int   length)   
  index:开始位置,从0开始     
  length:你要取的子字符串的长度  
例:

static void Main(string[] args)
{
string myString = "Hello Word!";

//Substring()在C#中有两个重载函数
//分别如下示例

string subString1 = myString.Substring(0);

//如果传入参数为一个长整, 且大于等于0,
//则以这个长整的位置为起始,
//截取之后余下所有作为字串.
//如若传入值小于0,
//系统会抛出ArgumentOutOfRange异常
//表明参数范围出界

string subString2 = myString.Substring(0, 5);

//如果传入了两个长整参数,
//前一个为参数子串在原串的起始位置
//后一个参数为子串的长度
//如不合条件同样出现上述异常

Console.WriteLine(subString1);
Console.WriteLine(subString2);
Console.ReadLine();
}

程序输出的结果:
Hello Word!
Hello
 
 
 
转自:https://www.cnblogs.com/yuerdongni/archive/2011/10/09/2204806.html
转自:https://www.cnblogs.com/nextsoft/articles/782336.html
原文地址:https://www.cnblogs.com/zeng-qh/p/9878181.html