【问题标题】:Is there a way to point to a certain section of a string in C?有没有办法指向 C 中字符串的某个部分?
【发布时间】:2022-08-11 03:26:43
【问题描述】:

我想指向字符数组的某个部分,即:

char string[] = \"the quick brown fox jumps over the lazy dog\";
char * pointer = points to the \'fox\' part of string;

这可以在不使用 strncpy 或类似的东西的情况下完成吗?

  • 像字符串 +17 ?
  • pointer = &string[17];
  • 另外:pointer = strstr(string, \"fox\"); - 这将扫描string 以查找短语\"fox\" 的第一次出现并返回指向它的指针。
  • 那些将是fox jumps over the lazy dog,而不是fox
  • @JosephSible-ReinstateMonica - 正确。

标签: c string pointers char


【解决方案1】:

strstr() 或类似的用户代码可用于在细绳.

const char *haystack = "the quick brown fox jumps over the lazy dog";
const char *target = "fox";

char *needle = strstr(haystack, target);

打印字符串的一部分,如"fox",使用精确.

if (needle == NULL) {
  printf("<%s> not found.\n");
} else {
  ptrdiff_t offset = needle - haystack;
  int precision = (int) strlen(target);
  printf("<%.*s> found at offset %td.\n", precision, needle, offset);
}

【讨论】:

  • 请注意strstr 会默默地丢弃const 指针,因此当您之后想要对needle 执行操作时,如果haystack 是字符串文字,这可能会导致问题。这个例子很好,但如果你试图修改字符串文字,请小心。
  • @chux:呵呵,你得到了ptrdiff_t 的转换格式说明符吧。 :)
【解决方案2】:

在不复制或修改字符串的情况下,您只能指向具有相同结尾的子字符串(例如,fox jumps over the lazy dogdoglazy dog),而不能指向以原始字符串中间结尾的子字符串,例如 foxlazy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多