如果所有字符串都需要一个长度或空终止符,那么高级语言如何只用字符构造一个字符串?

所以我正在编写一些 C 代码来模拟脚本语言。我遇到了一个场景,如果我运行一个函数来导入文件,比如说import("file.c")我遇到了一个问题,我不一定可以使用指针,因为它不是以空值终止的。我还需要给出字符串的长度import("file.c", 5)或使用空终止字符import("file.c\0")。我假设使用缓冲区是使用固定大小的方法,例如char file_name[256]它可能覆盖足够大的文件名。但这引发了一些关于“高级”编程语言(例如 Python 或 Golang)的有趣问题。所以 Golong 的导入从互联网搜索中看起来是这样的:


import (

    "fmt"

    "math"

)

我会假设这些库被视为字符串,不是吗?蟒蛇呢?


import pandas as pd

import math

import functools

那些也被视为字符串吗?至少,对我来说,我会假设 golang 的进口是。但是让我们完全忘记导入。只是字符串呢?Python的字符串是:


s = "I like Apple Pie"

我在这里看到golang 中的字符串定义为:


type _string struct {

    elements *byte // underlying bytes

    len      int   // number of bytes

}

然后下一段代码说:


const World = "world"

没有指定 len 的地方。是什么赋予了?


golang,或者一般来说,“更高”级别的语言如何使用字符串,而不必指定以空结尾的字符串或带数字的长度?还是我完全错过了什么?


我来自 Python 背景和一些 C,但在今天的大多数编程语言中似乎非常相似。


叮当猫咪
浏览 160回答 2
2回答

呼啦一阵风

您不为字符串文字编写字符串长度或空终止字符这一事实并不意味着它不能自动完成:编译器可以做到(因为它在编译时知道字符串长度)并且很可能正在做它。例如在C中:空字符('\0'、L'\0'、char16_t() 等)始终附加到字符串文字:因此,字符串文字“Hello”是包含字符“H”的 const char[6] 、'e'、'l'、'l'、'o' 和 '\0'。这是一个小型 C 程序,显示空字符附加到字符串文字:#include <stdio.h>#include <string.h>int main(){&nbsp; &nbsp;char *p="hello";&nbsp; &nbsp;int i;&nbsp; &nbsp;i = 0;&nbsp; &nbsp;&nbsp; &nbsp;while (p[i] != '\0')&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; printf("%c ", p[i]);&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp;}&nbsp; &nbsp;printf("\nstrlen(p)=%ld\n", strlen(p));&nbsp; &nbsp;return 0;}执行:./helloh e l l o&nbsp;strlen(p)=5您还可以使用以下命令在调试模式下编译程序:gcc -g -o hello -Wall -pedantic -Wextra hello.c并检查gdb:&nbsp; &nbsp; gdb hello&nbsp; &nbsp; ...&nbsp; &nbsp; (gdb) b main&nbsp; &nbsp; Breakpoint 1 at 0x400585: file hello.c, line 6.&nbsp; &nbsp; (gdb) r&nbsp; &nbsp; Starting program: /home/pifor/c/hello&nbsp;&nbsp; &nbsp; Breakpoint 1, main () at hello.c:6&nbsp;&nbsp;&nbsp; &nbsp; 6&nbsp; &nbsp; &nbsp; char *p="hello";&nbsp; &nbsp; (gdb) n&nbsp; &nbsp; 9&nbsp; &nbsp; &nbsp; i = 0;&nbsp; &nbsp;&nbsp; &nbsp; (gdb) print *(p+5)&nbsp; &nbsp; $7 = 0 '\000'&nbsp; &nbsp; (gdb) print *(p+4)&nbsp; &nbsp; $8 = 111 'o'&nbsp;&nbsp; &nbsp; (gdb) print *p&nbsp; &nbsp; $10 = 104 'h'

Qyouu

Go 中的字符串值是指向字节和长度的指针。这是Go 对 type 的定义:type StringHeader struct {&nbsp; &nbsp; Data uintptr&nbsp; &nbsp; Len&nbsp; int}对于类似 的字符串文字"world",编译器会计算字节数以设置长度。StringHeader{Data: pointerToBytesWorld, Len: 5}文字在运行时由 表示 。长度通过切片表达式隐含在字符串值的切片操作数中:&nbsp;s := "Hello"&nbsp;s = s[1:4]&nbsp; &nbsp;// length is 4 - 1 = 3字符串转换取操作数的长度:&nbsp;b := []byte{'F', 'o', 'p'}&nbsp;s = string(b)&nbsp; // length is 3, same as len(b)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go