简体   繁体   English

如何在没有正则表达式或任何外部方法的情况下摆脱双空格?

[英]How do I get rid of double spaces without regex or any external methods?

This is an extra exercise given to us on our Uni course, in which we need to find whether a sentence contains a palindrome or not.这是我们大学课程给我们的额外练习,我们需要找出一个句子是否包含回文。 Whereas finding if a word is a palindrome or not is fairly easy, there could be a situation where the given sentence looks like this: "Dog cat - kajak house".虽然判断一个词是否为回文相当容易,但可能存在给定句子如下所示的情况:“Dog cat - kajak house”。 My logic is to, using functions I already wrote, first determine if a character is a letter or not, if not delete it.我的逻辑是,使用我已经写过的函数,首先确定一个字符是否是一个字母,如果不是就删除它。 Then count number of spaces+1 to find out how many words there are in a sentence, prepare an array of those words and then cast a function that checks if a word is palindrome on every element of an array.然后计算空格数 + 1 以找出句子中有多少个单词,准备这些单词的数组,然后投射 function 检查数组的每个元素上的单词是否为回文。 However, the double space would mess everything up on a "counting" phase.然而,双倍空间会在“计数”阶段搞砸一切。 I've spent around an hour fiddling with code to do this, however I can't wrap my head around this.我花了大约一个小时来摆弄代码来执行此操作,但是我无法解决这个问题。 Could anyone help me?谁能帮帮我? Note that I'm not supposed to use any external methods or libraries.请注意,我不应该使用任何外部方法或库。 I've done this using RegEx and it was fairly easy, however I'd like to do this "legally".我已经使用 RegEx 完成了这项工作并且相当容易,但是我想“合法”地执行此操作。 Thanks in advance!提前致谢!

Just split on space, the trick is to remove empties.只是在空间上分裂,诀窍是去除空的。 Google StringSplitOptions.RemoveEmptyEntries谷歌StringSplitOptions.RemoveEmptyEntries

then obviously join with one clean space然后显然加入一个干净的空间

You could copy all the characters you are interested in to a new string:您可以将您感兴趣的所有字符复制到一个新字符串中:

var copy = new StringBuilder();

// Indicates whether the previous character was whitespace
var whitespace = true;

foreach (var character in originalString)
{
    if (char.IsLetter(character))
    {
        copy.Append(character);
        whitespace = false;
    }
    else if (char.IsWhiteSpace(character) && !whitespace)
    {
        copy.Append(character);
        whitespace = true;
    }
    else
    {
        // Ignore other characters
    }
}

If you're looking for the most rudimentary/olde-worlde option, this will work.如果您正在寻找最基本的/olde-worlde 选项,这将起作用。 But no-one would actually do this, other than in an illustrative manner.但是除了说明性的方式之外,没有人会真正这样做。

string test = "Dog cat       kajak house"; // Your string minus any non-letters
int prevLen;
do
{
    prevLen = test.Length;
    test = test.Replace("  ", " "); // Repeat-replace double spaces until none left
} while (prevLen > test.Length);

Personally, I'd probably do the following to end up with an array of words to check:就个人而言,我可能会执行以下操作以得到一组要检查的单词:

string[] words = test.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM