ninjatogo
ninjatogo

Reputation: 63

How to check if string character is a space?

I've just started programming in C#. I'm trying to build a simple Vigenere text encryption tool as a personal project.

My problem should be very easy to fix, yet it's really stressing me out to find the error. In my code I'm trying to do a simple check to see whether or not the character in my string is a space; I have set up my if statement properly yet it is skipping the first test and moving to the else if, even when the first test is true. Id really like some help on this one.

My problem area is at the bottom.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class fun2013
{
public static void Main()
{
    Console.WriteLine("fun 2013");
    string UserName;
    do
    {
        Console.Write("LOGIN//: ");
        UserName = Console.ReadLine();
    }
    while(UserName != "Max");
    Console.WriteLine(("Hello ") + (UserName) + (", enter your key below."));

                //USER ENTERS TEXT AT THIS POINT

    string loweredPass = Console.ReadLine().ToLower();
        Console.WriteLine("Changing CASE...");
        Console.WriteLine(loweredPass);
    string Strippedpass = loweredPass.Replace(" ","");
        Console.WriteLine("STRIPPING SPACES...");
        Console.WriteLine(Strippedpass);
    int passLength = Strippedpass.Length;
        Console.WriteLine("Enter your message below.");
    string userMessage = Console.ReadLine();
    int MessageLength = userMessage.Length;

                //BEGIN PROCESSING STRINGS INTO ARRAYS

    string temp = "";
    StringBuilder bcon = new StringBuilder();
    char [] passArray = Strippedpass.ToCharArray();
    char [] messArray = userMessage.ToCharArray();
    string letterf = "";

    for(int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
        {
        >>> if (messArray[i].ToString() == " ")
            {
                letterf = " ";
            }
        else if (messArray[i].ToString() != " ")
            {
                letterf = passArray[i].ToString();
            }
            if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
                {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
        temp = letterf;
        bcon.Append(temp);
        }

    Console.WriteLine();
    Console.WriteLine(bcon);


    Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine(); //KILL APPLICATION
}
}

Thanks for the help everyone, but after further inspection I noticed I made an error in my for loop. I was resetting the message array reader using the same interval as the key array (int i). I changed it to use the correct integer, "j". I also put the "temp" string updater and string builder into each if statement in the loop. It's now running correctly.

    for (int i=0, j=0; j < (MessageLength); i++, j++)    //i used for key array, j used for message length
    {

    if (messArray[j].ToString() != " ")
        {
            letterf = passArray[i].ToString();
            temp = letterf;
            bcon.Append(temp);
        }

    else if (messArray[j].ToString() == " ")
        {
            letterf = " ";
            temp = letterf;
            bcon.Append(temp);
        }

    if (i >= (passLength-1))    //array starts at value 0, length check starts at 1. Subtract 1 to keep them equal
        {i = -1;}   //-1 is used so it will go back to value of 0 on next loop
    }

Upvotes: 6

Views: 21556

Answers (5)

WesleyAC
WesleyAC

Reputation: 553

You should be able to do this:

if (messArray[i] == ' ') // to check if the char is a single space

Upvotes: 0

Andrew Morton
Andrew Morton

Reputation: 25013

You seem to have missed out the essential part of the cipher, which is to offset the message letters by an amount depending on the key letters. Also, you'll want to ignore any characters which can't be enciphered to a letter: ":", "!", "," and so on, not just spaces.

Spoiler alert

using System;
using System.Text;
using System.Text.RegularExpressions;

public class fun2013
{
    public static void Main()
    {
        Console.WriteLine("fun 2013");
        string userName = "";
        do
        {
            Console.Write("LOGIN//: ");
            userName = Console.ReadLine();
        }
        while (userName != "Max");
        Console.Write("Hello " + userName + ", enter your key: ");

        // Get a user-input key and make sure it has at least one usable character.
        // Allow only characters [A-Za-z].
        string viginereKey;
        do
        {
            viginereKey = Console.ReadLine();
            // remove everything which is not acceptable
            viginereKey = Regex.Replace(viginereKey, "[^A-Za-z]", "");
            if (viginereKey.Length == 0)
            {
                Console.Write("Please enter some letters (A-Z) for the key: ");
            }
        }
        while (viginereKey.Length == 0);

        // no need to create a new variable for the lowercase string
        viginereKey = viginereKey.ToLower();
        // "\n" in a string writes a new line
        Console.WriteLine("Changing CASE...\n" + viginereKey);

        int keyLength = viginereKey.Length;

        Console.WriteLine("Enter your message:");
        string message = Console.ReadLine();
        message = message.ToLower();
        int messageLength = message.Length;

        StringBuilder cipherText = new StringBuilder();

        // first and last characters to encipher
        const int firstChar = (int)'a';
        const int lastChar = (int)'z';
        const int alphabetLength = lastChar - firstChar + 1;

        int keyIndex = 0;

        for (int i = 0; i < messageLength; i++)
        {
            int thisChar = (int)message[i];

            // only encipher the character if it is in the acceptable range
            if (thisChar >= firstChar && thisChar <= lastChar)
            {
                int offset = (int)viginereKey[keyIndex] - firstChar;
                char newChar = (char)(((thisChar - firstChar + offset) % alphabetLength) + firstChar);
                cipherText.Append(newChar);

                // increment the keyIndex, modulo the length of the key
                keyIndex = (keyIndex + 1) % keyLength;
            }
        }

        Console.WriteLine();
        Console.WriteLine(cipherText);

        Console.WriteLine("Press ENTER to continue...");
        Console.ReadLine(); // Exit program
    }
}

Upvotes: 0

Justin Lessard
Justin Lessard

Reputation: 11901

Char.IsWhiteSpace(char)

See also the String.IsNullOrEmpty or String.IsNullOrWhiteSpace.

Upvotes: 6

Cornel Marian
Cornel Marian

Reputation: 2503

Try

Char.IsWhiteSpace(character)

Sample from msdn:

public class IsWhiteSpaceSample {
public static void Main() {
    string str = "black matter"; 

    Console.WriteLine(Char.IsWhiteSpace('A'));      // Output: "False"
    Console.WriteLine(Char.IsWhiteSpace(str, 5));   // Output: "True"
}
}

Upvotes: 0

oleksii
oleksii

Reputation: 35905

I'm trying to do a simple check to see whether or not the character in my string is a space;

You can change this code

messArray[i].ToString() != " "

to

char.IsWhiteSpace(messArray[i])

Upvotes: 1

Related Questions