【发布时间】:2018-12-02 11:15:58
【问题描述】:
我必须编写一个程序来检查输入是否是回文,并且在这段代码中,我需要有一个从字符串中删除所有非字母字符的方法。做这个的最好方式是什么?将输入转换为数组是否更好(现在我将其作为字符串进行)?我不想为每个单独的字符编写一个循环或将每个字符都放入修剪中。修剪也会去掉中间的东西吗?
我也不允许使用正则表达式、可枚举或抛出新异常,因为教授不喜欢后两者,第一个不起作用,它只会抛出错误。
我这样做的方式似乎不是解决这个问题的最有效方式。
我的代码在这里:
public partial class frmPalindrome : Form
{
public frmPalindrome()
{
InitializeComponent();
}
//allows btnCheck to take in user input in txtEnterWordPhrase and check if it is a palindrome
private void btnCheck_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
string strPhrase = Convert.ToString(txtEnterWordPhrase.Text);
string strCleanPhrase = CharacterStrip(strPhrase);
txtPalindrome.Text = Convert.ToString(IsPalindrome(strCleanPhrase));
}
}
catch (Exception ex) //catches any other exceptions
{
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception");
}
}
//a method that cuts all the nonalphabetic characters out of txtEnterWordPhrase
public string CharacterStrip(string Phrase)
{
//neither of these seem very efficient
//Phrase = Phrase.Trim(new Char[] {' ', '&', '*', ',', '-', '_', '/', '\', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', });
while (Phrase.IndexOf(" ") >= 0)
{
int intIndex = Phrase.IndexOf(" ");
Phrase.Remove(intIndex, 1);
}
return Phrase;
}
//checks if the input is a palindrome
public bool IsPalindrome(string Phrase)
{
//not sure how to do this yet
return true; //have not built this method yet
}
//checks that the input is valid
public bool IsValidData ()
{
return IsString(txtEnterWordPhrase, "Enter a Word or Phrase"); //have not built this validation method yet
}
//checks that the input in txtEnterWordPhrase is a string
public bool IsString(TextBox Textbox, string Name)
{
decimal Number = 0m;
if (Decimal.TryParse(Textbox.Text, out Number))
{
MessageBox.Show(Name + " must be a word or phrase.", "Entry Error");
return false;
}
else
return true;
}
//allows btnExit to close the program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
//a method that clears txtPalindrome and returns focus to txtEnterWordPhrase
private void ClearResults(object sender, EventArgs e)
{
txtPalindrome.Text = "";
txtEnterWordPhrase.Focus();
}
}
【问题讨论】:
-
为什么您认为使用 .Trim 效率如此之低?我会说它的工作效率很高,但它并没有达到我认为您期望的效果;它只会从字符串的开头和结尾删除这些字符。
-
@andresairr 我没有意识到它只是开始和结束,我正在寻找在整个字符串中都有效的东西。如果用户输入“test 12 test”我需要把它变成“testtest”
-
Code Review(提问前记得阅读帮助)
-
@user202729 你只是想给我看另一个网站吗?
标签: c#