简体   繁体   English

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

[英]How to check if string character is a space?

I've just started programming in C#.我刚开始用 C# 编程。 I'm trying to build a simple Vigenere text encryption tool as a personal project.我正在尝试构建一个简单的 Vigenere 文本加密工具作为个人项目。

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.我已经正确设置了 if 语句,但它跳过第一个测试并移动到 else if,即使第一个测试为真。 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.感谢大家的帮助,但经过进一步检查后,我注意到我的 for 循环出错了。 I was resetting the message array reader using the same interval as the key array (int i).我正在使用与键数组 (int i) 相同的间隔重置消息数组读取器。 I changed it to use the correct integer, "j".我将其更改为使用正确的整数“j”。 I also put the "temp" string updater and string builder into each if statement in the loop.我还将“临时”字符串更新器和字符串生成器放入循环中的每个 if 语句中。 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
    }

Char.IsWhiteSpace(char) Char.IsWhiteSpace(char)

See also the String.IsNullOrEmpty or String.IsNullOrWhiteSpace .另请参阅String.IsNullOrEmptyString.IsNullOrWhiteSpace

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])

Try试试

Char.IsWhiteSpace(character) Char.IsWhiteSpace(字符)

Sample from msdn :来自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"
}
}

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

你应该能够做到这一点:

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

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

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