如何在两个指针之间打印字符串?
How do I print a string between two pointers?
我正在为 Elon Musk 建造火箭,内存使用对我来说非常重要。
我有文本和指向它的指针 pText
。堆里真让人不寒而栗。
有时我需要分析字符串,它的单词。我不在堆中存储子字符串,而是存储两个指针 start/end 用于表示文本的子字符串。但有时我需要打印这些子字符串以进行调试。我该怎么做?
我知道要打印一个字符串,我需要两件事
- 指向乞讨的指针
- 末尾为空终止符
有什么想法吗?
// Text
char *pText = "We've sold the Earch!";
// Substring `sold`
char *pStart = &(pText + 6) // s
char *pEnd = &(pStart + 3) // d
// Print that substring
printf("sold: %s", ???);
如果您只想打印 子字符串,则为printf
使用精度参数:
printf("sold: %.*s", (int) (pEnd - pStart) + 1, pStart);
如果您需要以其他方式使用子字符串,那么最简单的方法可能是创建一个临时字符串,将其复制到其中,然后打印出来。
也许是这样的:
// Get the length of the sub-string
size_t length = pEnd - pStart + 1;
// Create an array for the sub-string, +1 for the null-terminator
char temp[length + 1];
// Copy the sub-string
memcpy(temp, pStart, length);
// Terminate it
temp[length] = '[=11=]';
如果您需要多次执行此操作,我建议您为此创建一个通用函数。
您可能还需要根据用例使用 malloc
动态分配字符串。
我正在为 Elon Musk 建造火箭,内存使用对我来说非常重要。
我有文本和指向它的指针 pText
。堆里真让人不寒而栗。
有时我需要分析字符串,它的单词。我不在堆中存储子字符串,而是存储两个指针 start/end 用于表示文本的子字符串。但有时我需要打印这些子字符串以进行调试。我该怎么做?
我知道要打印一个字符串,我需要两件事
- 指向乞讨的指针
- 末尾为空终止符
有什么想法吗?
// Text
char *pText = "We've sold the Earch!";
// Substring `sold`
char *pStart = &(pText + 6) // s
char *pEnd = &(pStart + 3) // d
// Print that substring
printf("sold: %s", ???);
如果您只想打印 子字符串,则为printf
使用精度参数:
printf("sold: %.*s", (int) (pEnd - pStart) + 1, pStart);
如果您需要以其他方式使用子字符串,那么最简单的方法可能是创建一个临时字符串,将其复制到其中,然后打印出来。
也许是这样的:
// Get the length of the sub-string
size_t length = pEnd - pStart + 1;
// Create an array for the sub-string, +1 for the null-terminator
char temp[length + 1];
// Copy the sub-string
memcpy(temp, pStart, length);
// Terminate it
temp[length] = '[=11=]';
如果您需要多次执行此操作,我建议您为此创建一个通用函数。
您可能还需要根据用例使用 malloc
动态分配字符串。