如何将数组索引实现的三空格替换代码改为指针算术操作?
Alright, let's refactor your array-index-based code to use pointer arithmetic instead. Here's the complete working version, mapped directly to your original logic:
// Assume tmp0_pointer is initialized in main as: char *tmp0_pointer = buffer; while (*tmp0_pointer != '\0') { // Check for three consecutive spaces using pointer offsets if (*tmp0_pointer == ' ' && *(tmp0_pointer + 1) == ' ' && *(tmp0_pointer + 2) == ' ') { *tmp0_pointer = '*'; // Replace the first space with * via pointer dereference putchar(*tmp0_pointer); tmp0_pointer += 2; // Skip the next two spaces (equivalent to i += 2) continue; } putchar(*tmp0_pointer); tmp0_pointer++; // Move to the next character (equivalent to i++) }
Key Conversion Details
Let's break down how each part of your original code maps to pointer arithmetic:
- Array index to pointer dereference:
buffer[i]is exactly equivalent to*tmp0_pointerwhentmp0_pointerstarts atbufferand increments the same wayidoes. - Offset access:
buffer[i+1]andbuffer[i+2]become*(tmp0_pointer + 1)and*(tmp0_pointer + 2). Pointer arithmetic automatically accounts for the size of thechartype (1 byte here), so the offset logic matches array indexing perfectly. - Index increments:
i++becomestmp0_pointer++(moves the pointer to the next character in the buffer)i = i + 2becomestmp0_pointer += 2(jumps the pointer two positions forward to skip the remaining spaces)
- Loop termination: The original loop's implicit end condition (stopping when the end of the string is reached) is replaced with checking if the dereferenced pointer (
*tmp0_pointer) is the null terminator'\0'.
Note on Safety
Just like your original code, this implementation assumes that when we check for three consecutive spaces, there are actually three valid characters left in the buffer (i.e., we don't hit the null terminator mid-check). If you need to handle edge cases where the string ends with 1 or 2 spaces, you'd add extra checks for *(tmp0_pointer + 1) != '\0' and *(tmp0_pointer + 2) != '\0' in the if condition—but that's beyond the scope of just converting to pointer arithmetic.
内容的提问来源于stack exchange,提问作者user8862019

