如何检查字符串中的字符是否为空格?

6
我刚开始学习C#编程。我试图构建一个简单的Vigenere文本加密工具作为个人项目。
我的问题应该很容易解决,但是找到错误真的让我很烦恼。在我的代码中,我试图进行一个简单的检查,以查看字符串中的字符是否为空格; 我已经正确设置了if语句,但它跳过了第一个测试并移动到else if,即使第一个测试为真。我真的需要一些帮助。
我的问题区域在底部。
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
}
}

感谢大家的帮助,但经过进一步检查,我发现在我的for循环中犯了一个错误。我使用了与密钥数组相同的间隔(int i)来重置消息数组阅读器。我将其更改为使用正确的整数“j”。我还将“temp”字符串更新程序和字符串生成器放入了循环中的每个if语句中。现在它正在正常运行。

    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
    }

我建议先让它适用于简单的情况,比如键为“b”,消息为“hello”。然后再考虑更长的键和非字母字符。 - Andrew Morton
你的代码只输出密钥中的字母,例如如果我使用“a”作为密钥,“hello”作为消息,则输出“aaaaa”,而不是应该输出“hello”,同样地(“ab”,“hello”)->“ababa”。这绝对不是Vigenère密码的预期行为。 - Andrew Morton
5个回答

6

出于某种原因,这仍然跳过了我的测试。 - ninjatogo
你说的跳过是什么意思?是指它的值为假吗?还是代码根本没有运行? - Black Frog
如果我将比较字符串更改为除空格字符以外的任何内容,则该语句将运行。否则,它将采用else if路线。 - ninjatogo
所以,我看到了困惑。实际的代码需要像这样,例如从您的代码中,--> Char.IsWhiteSpace(messArray[i])。 - WesleyAC

1
我将尝试进行简单的检查,以确定字符串中的字符是否为空格; 您可以更改此代码。
messArray[i].ToString() != " "

char.IsWhiteSpace(messArray[i])

你能否添加 >>> 来准确显示出问题所在的那一行? - oleksii
当然,它在for循环中。 - ninjatogo
如果我理解正确的话,这行代码 Console.WriteLine(bcon); 会打印一个空格,但因为它是控制台应用程序,所以你看不到它。你能用调试器逐步执行吗?比较应该在任何情况下都有效,我怀疑逻辑上存在问题。 - oleksii

0

尝试

Char.IsWhiteSpace(character)

来自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"
}
}

0

你似乎错过了密码的关键部分,即根据密钥字母偏移消息字母的数量。此外,您需要忽略任何无法加密为字母的字符:“:”,“!”,“,”等,而不仅仅是空格。

剧透警告

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
    }
}

谢谢你的帮助,但我发的只是我代码中的一小部分,整个代码都有问题。虽然你的代码更短且可以处理大小写(更加实用),我也会看一下你的代码。 - ninjatogo

0
你应该能够做到这一点:
if (messArray[i] == ' ') // to check if the char is a single space

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接