/*
假设有一字符串strS="This Is An Apple.",使用字符串方法,完成下面的要求。
(1)取出字符串strS中的第9个字符,然后统计该字符串strS中出现的次数。
(2)统计字符串中单词的个数。
(3)将字符串反序并全部转换为大写字符输出。
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cx
{
class Program
{
static void Main(string[] args)
{
string strS = "This Is An Apple.";
if (!string.IsNullOrEmpty(strS)) //判断是否为空
{
char findChar = Convert.ToChar(strS.Substring(8, 1)); //从字符串strS的startIndex开始取length个字符
int count = GetCharCount(strS, findChar);
string[] word = strS.Split(' '); //将字符串按空格分离成二维数组
int len = word.Length;
string strSReverse1 = MyReverse1(strS).ToUpper(); //将其转换成大写
Console.WriteLine("\"This Is An Apple.\"共有{0}个单词,{1}出现了{2}次", len, findChar, count);
Console.WriteLine(strSReverse1);
string strSReverse2 = MyReverse2(strS).ToUpper(); //将其转换成大写
Console.WriteLine("\"This Is An Apple.\"共有{0}个单词,{1}出现了{2}次", len, findChar, count);
Console.WriteLine(strSReverse2);
}
else
Console.WriteLine("字符串为空");
Console.ReadKey();
}
public static int GetCharCount(string strS, char findChar) //计算字符findChar的个数
{
int count = 0;
char[] c = strS.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)
{
if (c[i] == findChar)
count++;
}
return count;
}
public static string MyReverse1(string strS) //将字符串strs反序
{
string strreverse = "";
char[] c = strS.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)
strreverse += c[i].ToString();
return strreverse;
}
public static string MyReverse2(string strS) //将字符串strS反序
{
StringBuilder strReverse = new StringBuilder();
char[] c = strS.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)
{
strReverse.Append(c[i]);
}
return strReverse.ToString();
}
}
}
运行结果:
/*
实验StringBuilder类。定义一个静态成员方法,该方法实现字符串反转。
如:Reverse("6221982")返回值为2891226。
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cx
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("数组反序后为:{0}",Reverse("6221982"));
Console.ReadKey();
}
// 代码出现超限错误
public static string Reverse(string strs) //将字符串strs反序
{
StringBuilder strreverse = new StringBuilder();
char[] c = strs.ToCharArray();
for (int i = c.Length - 1; i >= 0; i--)
{
strreverse.Append(c[i]);
}
return strreverse.ToString();
}
}
}
运行结果: