string字符串的一系列操作


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。

substr(start[,length])表示从start位置开始取length个字符串
substring(start,end)表示从start,到end之间的字符串,包括start位置的字符但是不包括end位置的字符
C#的Substring

语法:

程序代码
String.Substring(int startIndex)
String.Substring(int startIndex, int length)

说明:
返回一个从startIndex开始到结束的子字符串,或返回一个从startIndex开始,长度为length的子字符串。



用户输入一个字符串,将字符串以与输入相反的顺序输出:
using System;
namespace Test { class T1 { public static void Main() { Console.WriteLine("input the string "); string mystring = Console.ReadLine(); char[] past = mystring.ToCharArray(); char[] change = new char[past.Length]; for (int x = 0; x < past.Length; x++) { change[x] = past[past.Length - 1 - x]; } Console.Write(change); Console.ReadLine(); } } }

用户输入一个字符串,将其中的每个字符都加上双引号:
using System;
namespace Test
{
    class Addyinhao
    {
        public static void Main()
        {
            Console.WriteLine("input the string ");
            string mystring = Console.ReadLine();
            string changstring = "";
            foreach(char a in mystring)
            { 
            changstring+="\""+a+"\"";
            }
            Console.WriteLine(changstring);
            Console.ReadLine();

        }
    }
}

注:在引号中用引号 需要加上转义字符 \ 这样才能正确使用。

 

用户输入一个字符串,用yes替换字符串中的no:
using System;
namespace Test
{
    class YesReplaceNo
    {
        public static void Main()
        {
            Console.WriteLine("input the string ");
            string mystring = Console.ReadLine();
            string changstring = "";
            changstring = mystring.Replace("no", "yes");
            Console.WriteLine(changstring);
            Console.ReadLine();

        }
    }
}

 

 

 

posted @ 2014-03-11 11:58  苦力劳动者  阅读(275)  评论(0编辑  收藏  举报