编写控制台程序,接收一个长度大于3的字符串
问题描述:
1)编写个控制台程序,接收一个长度大于3的字符串,完成下列功能。
①输出字符串的长度。
②输出字符串中第一 一个出现字母a的位置。。
③在字符串的第3个字符后面插入子串"hello",输出新字符串。
④将字符串"hello"替换为"me",输出新字符串。
⑤以字符"m”为分隔符,将字符串分离,并输出分离后的字符串。
答
using System;
class Test6
{
public static void Main()
{
string str = "";
while (str.Length <= 3)
{
Console.Write("请输入一个长度大于3的字符串:");
str = Console.ReadLine();
}
//(1)
Console.WriteLine("字符串的长度为:{0}", str.Length);
//(2)
int i = str.IndexOf('a');
if (i > -1)
{
Console.WriteLine("第一个出现字母a的位置是:{0}", i);
}
else
{
Console.WriteLine("字符串中不包含字母a。");
}
//(3)
string str1 = str.Insert(3, "hello"); //在第3个(初始序号为)字符前插入hello
Console.WriteLine("插入hello后的结果为:{0}", str1);
//(4)
string str2 = str1.Replace("hello", "me");
Console.WriteLine("将hello替换为me后的结果为:{0}", str2);
//(5)
string[] arr = str2.Split('m');
Console.WriteLine("以m为分隔符分离后的字符串有:");
for (int j = 0; j < arr.Length; j++)
{
Console.WriteLine(arr[j]);
}
}
}
答
题主要的代码如下,有帮助麻烦点下【采纳该答案】,谢谢~~有其他问题可以继续交流~
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string s = Console.ReadLine();
Console.WriteLine(s.Length);
Console.WriteLine(s.IndexOf("a"));
s = s.Insert(3, "hello");
Console.WriteLine(s);
s = s.Replace("hello", "me");
Console.WriteLine(s);
string[] arr = s.Split('m');
Console.WriteLine(String.Join(",", arr));
Console.ReadKey();
}
}
}