所以我正在编写一些 C 代码来模拟脚本语言。
我遇到了一个场景,如果我运行一个函数来导入文件,比如 import("file.c")
我遇到了一个问题,我不一定可以使用指针,因为它不是空终止的。我还需要给出字符串的长度,如 import("file.c", 5)
或使用空终止字符 import("file.c\0")
.我假设使用缓冲区是固定大小的方法,例如 char file_name[256]
这可能涵盖了足够大的文件名。但这引发了一些关于“高级”编程语言(例如 Python 或 Golang)的有趣问题。所以 Golong 的导入从互联网搜索中看起来是这样的:
import (
"fmt"
"math"
)
我会假设这些库被视为字符串,不是吗? python 呢?
import pandas as pd
import math
import functools
那些也被视为字符串吗?至少,对我来说,我会假设 golang 的进口是。
但是让我们完全忘记导入。只是字符串呢?
Python的字符串是:
s = "I like Apple Pie"
我看到了here golang 中的字符串定义为:
type _string struct {
elements *byte // underlying bytes
len int // number of bytes
}
然后下一段代码说:
const World = "world"
没有指定 len 的地方。是什么赋予了?
golang,或者一般来说,“更高”级别的语言如何使用字符串,而不必指定以空结尾的字符串或带数字的长度?还是我完全错过了什么?
我来自 Python 背景和一些 C,但在今天的大多数编程语言中似乎非常相似。
最佳答案
您不为字符串文字编写字符串长度或空终止字符这一事实并不意味着它不能自动完成:编译器可以做到(因为它在编译时知道字符串长度)并且很可能正在做它。
例如 C :
The null character ('\0', L'\0', char16_t(), etc) is always appended to the string literal: thus, a string literal "Hello" is a const char[6] holding the characters 'H', 'e', 'l', 'l', 'o', and '\0'.
这是一个小型 C 程序,显示空字符附加到字符串文字:
#include <stdio.h>
#include <string.h>
int main()
{
char *p="hello";
int i;
i = 0;
while (p[i] != '\0')
{
printf("%c ", p[i]);
i++;
}
printf("\nstrlen(p)=%ld\n", strlen(p));
return 0;
}
执行:
./hello
h e l l o
strlen(p)=5
您还可以使用以下命令在 Debug模式下编译程序:
gcc -g -o hello -Wall -pedantic -Wextra hello.c
并与
gdb
核对: gdb hello
...
(gdb) b main
Breakpoint 1 at 0x400585: file hello.c, line 6.
(gdb) r
Starting program: /home/pifor/c/hello
Breakpoint 1, main () at hello.c:6
6 char *p="hello";
(gdb) n
9 i = 0;
(gdb) print *(p+5)
$7 = 0 '\000'
(gdb) print *(p+4)
$8 = 111 'o'
(gdb) print *p
$10 = 104 'h'
关于python - 如果所有字符串都需要一个长度或空终止符,那么高级语言如何只用字符构造一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366296/