簡體   English   中英

如何檢查字符串字符是否為空格?

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

我剛開始用 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”。 我還將“臨時”字符串更新器和字符串生成器放入循環中的每個 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
    }

Char.IsWhiteSpace(char)

另請參閱String.IsNullOrEmptyString.IsNullOrWhiteSpace

我正在嘗試做一個簡單的檢查,看看我的字符串中的字符是否是空格;

您可以更改此代碼

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

char.IsWhiteSpace(messArray[i])

試試

Char.IsWhiteSpace(字符)

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

您似乎錯過了密碼的重要部分,即根據關鍵字母將消息字母偏移一定量。 此外,您將要忽略任何無法編碼為字母的字符:“:”、“!”、“,”等,而不僅僅是空格。

劇透警報

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