简体   繁体   中英

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". 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. 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". Thanks in advance!

Just split on space, the trick is to remove empties. Google 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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