【问题标题】:An integer instead of string? Why? [duplicate]一个整数而不是字符串?为什么? [复制]
【发布时间】:2020-12-14 04:15:28
【问题描述】:

我正在一起使用 C# 和 C++ 进行一些实验,现在我被困在这里。这段代码既适用于懂 C# 的人,也适用于懂 C++ 的人。

我的 C# 代码 -

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

namespace std {
    class MyCode {
        static void Main(string[] args) {
            string name = "helloWorld!";
            Console.WriteLine(name[0] + name[1] + name[2] + name[3] + name[4] + name[5]);
        }
    } 
}

我的 C++ 代码-

#include <iostream>
using namespace std;

int main() {
    string x = "helloWorld!";
    cout << x[0] + x[1] + x[2] + x[3] + x[4] + x[5] << endl;
    return 0;
}

这两个代码给出相同的输出 -

619


Process Finished.

我的预期输出 -

helloW


Process Finished.

【问题讨论】:

  • 好吧,你还有一个类型溢出(字节或字符不能超过 255 = 0xff)和隐式转换为更大的类型(int 的最大值为 0xffffffff),因为 619不能用 char/byte 表示。但是,您可以将具有 4 个字符(4*32 位)的字符串数组中的“hell”、“oWor”等组合成一个 int 数组(1*32 位)并显示这些数字。
  • @Soleil-MathieuPrévot 如果我使用字符而不是整数会怎样?我知道这会令人困惑,但有可能吗?
  • 好吧,看来您正在尝试在 c++/c# 上下文中使用 python 语法(它做了其他事情)。尝试将字节数组转换为另一种类型(int、long、long long):template&lt;class T&gt; T ToType(const byte* x) { T value{}; for (int i = 0; i &lt; sizeof T; i++) value += ((long)x[i] &amp; 0xffL) &lt;&lt; 8 * i; return value; }。你这样使用它:ToType&lt;long long&gt;(charArray) 和 unsigned char* charArray[someSize]
  • 一般来说,就像在数学中一样,你想知道 + 函数到底是做什么的。它的定义可以不同于通常的定义(来自Peano的算术),它在程序语言中不是阿贝尔,在python中它在参数是字符串时连接它们,这里它是在做一个非交换加法。

标签: c# c++ string


【解决方案1】:

所有x[i] 都是字符。 Char 存储一个表示字符的数值,具体取决于您使用的编码。当您执行x[i] + x[j] 时,您并没有将它们连接起来,您只是将它们的数值相加。

【讨论】:

  • 如果我使用字符而不是整数会怎样?我知道这会令人困惑,但有可能吗?
  • 如果你想连接你将不得不使用字符串。
猜你喜欢
  • 1970-01-01
  • 2018-06-08
  • 2020-08-07
  • 1970-01-01
  • 2013-11-02
  • 2023-02-15
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多