[英]Replacing multiple words in a string sentence C#
大家好,我不需要答案,但我想知道并找出我做错了什么。 作为初学者,我在学习中得到了一项非常“简单”的作业。 我需要创建一个字符串,在这个字符串中,我需要用其他单词替换一些单词而不使用 for 循环:(我也想打印它,但我不知道把 Console.WriteLine 放在哪里,谷歌搜索 1小时没有工作或问大学。
/* 练习:与 stringbuilder 一起使用 * cat 变成 littlecat * dog 变成 littledog * 鼠标变成 littlemouse * 必须用 a 替换的单词 * 不要使用循环 */
using System;
using System.Collections.Generic;
using System.Text;
namespace Opgavens_leerpad_3_oefening
{
class Program
{
static string Main(string[] args)
{
StringBuilder sb = new StringBuilder();
string dogCat = new string("Can the cat find the mouse without waking the dog.");
static string replacethisstring(string dogCat);
{
hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("dog", "littldog");
hondKat = dogCat.Replace("mouse", "littlemouse");
hondKat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
错误 CS5001:程序不包含适合入口点的静态“Main”方法(我不明白几乎没有任何程序以这个静态 Main args 开始?)
错误 CS8112:replacethisstring(string)' 是一个本地函数,因此必须始终有一个主体。 (我只是给了它一个主体,对吗?我打开 { 并关闭它 } 并用 return 替换。)
方法声明以;
结尾;
这就是CS8112的原因
Main 方法必须返回void
(或 'int' )您已将其修改为string
,这就是CS5001的原因
如果您希望程序在控制台上打印输出,请使用:
using System;
....
Console.WriteLine(output)
;
在具有主体的函数声明的末尾。namespace Opgavens_leerpad_3_oefening
{
class Program
{
public static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Can the cat find the mouse without waking the dog.");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine(); // To Stop the Console from closing.
static StringBuilder replacethisstring(StringBuilder dogCat)
{
dogCat = dogCat.Replace("cat", "littlecat");
dogCat = dogCat.Replace("dog", "littldog");
dogCat = dogCat.Replace("mouse", "littlemouse");
dogCat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
您可以将函数放置在 Main 内或外部。 通常,您会在 Main 类之外找到函数。
public static void Main(string[] args)
{
...
}
public static string replacethisstring(string dogCat)
{
...
}
有几个问题,如拼写错误、语法错误等。此外,该练习有一个需要与 stringbuilder 一起使用的条件。
所以,试试这个。
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
static StringBuilder replacethisstring(StringBuilder dogCat)
{
StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("the", "a");
hondKat = dogCat.Replace("dog", "littledog");
hondKat = dogCat.Replace("mouse", "littlemouse");
return hondKat;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.