【问题标题】:Convert Char Array to String in C# [duplicate]在C#中将Char数组转换为字符串[重复]
【发布时间】:2021-05-03 22:37:20
【问题描述】:

我是编程新手,尤其是 C#,我想我会从简单的东西开始,比如文本反向器。我想我会更进一步,并使其成为回文检查器。问题是我似乎无法将数组转换回字符串以将其检查为原始输入。

string Inp = "1";  // user input

Console.WriteLine("Input a word to reverse"); // user inputs word
Inp = Convert.ToString(Console.ReadLine()); // input gets converted to string

char[] charArray = Inp.ToCharArray(); // converts char to array
Array.Reverse(charArray); // reverses array

if (Inp == charArray) { // compares user input to the array - does not work
    Console.WriteLine(Inp + " is a Palindrome"); // writes the input with text afterwards
} else {
    Console.WriteLine(Inp + " is not a palindrome");
}

我已经尝试过Convert.ToString 和其他版本的东西,但它似乎没有用。我尝试创建 new string = (charArray) 来创建一个也不起作用的新字符串 bur。 谢谢。

编辑:它给了我这个错误:

运算符'=='不能应用于'string'和'char[]'类型的操作数

还有,有点不相关,但是是不是注释太多了?我应该少做吗? 我是否正确地问了这个问题,还是我做错了什么而错过了?

【问题讨论】:

  • if (Inp.SequenceEqual(charArray)) { // Palindrome } else { // no Palindrome } ,顺便说一句,您不需要将字符串转换为字符串。

标签: c# arrays


【解决方案1】:

我不明白你的问题是什么,这很有效:

代码:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main()
        {
            var chars = new[] {'a', 'b', 'c'};
            var s = new string(chars);
            Console.WriteLine(s);
        }
    }
}

结果:

abc

对于您的比较问题,这里有一个更可靠的方法:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main()
        {
            var sourceChars = new[] {'a', 'b', 'c'};
            var targetChars = new[] {'C', 'B', 'A'};

            Array.Reverse(sourceChars);

            var sourceString = new string(sourceChars);
            var targetString = new string(targetChars);

            var isMatch = string.Equals(sourceString, targetString, StringComparison.OrdinalIgnoreCase);

            Console.WriteLine(isMatch);
        }
    }
}

结果:

是的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2016-09-05
    • 2012-10-03
    • 2016-08-13
    • 2012-10-28
    • 2015-08-01
    相关资源
    最近更新 更多