printf("\nString 3: \"%s\"\n", str3); printf("Length of str3 (strlen): %u\n", (unsignedint)len3);
printf("\n--- Important Note ---\n"); printf("String 4 is not null-terminated. Calling strlen on it leads to undefined behavior.\n"); printf("It might crash or run forever. Uncommenting the next lines is dangerous.\n"); /* 危险!不要对没有 \0 的字符串调用 strlen */ /* printf("Length of str4 (UNDEFINED BEHAVIOR!): %u\n", (unsigned int)strlen(str4)); */
if (result_ptr != NULL) { printf("First occurrence of '%c' found at position: %ld\n", target_char, (long)(result_ptr - str)); /* 计算偏移量 */ printf("Substring from first '%c': \"%s\"\n", target_char, result_ptr);
/* 查找下一个 's' */ printf("\n--- Searching for next occurrence ---\n"); result_ptr = strchr(result_ptr + 1, (int)target_char); /* 从下一个位置开始搜索 */ if (result_ptr != NULL) { printf("Second occurrence of '%c' found at position: %ld\n", target_char, (long)(result_ptr - str)); printf("Substring from second '%c': \"%s\"\n", target_char, result_ptr); } else { printf("No more occurrences of '%c' found.\n", target_char); }
} else { printf("Character '%c' not found in the string.\n", target_char); }
/* 查找字符串结尾符 '\0' */ printf("\n--- Searching for null terminator ---\n"); result_ptr = strchr(str, '\0'); if (result_ptr != NULL) { printf("Null terminator '\\0' found at position: %ld\n", (long)(result_ptr - str)); printf("Pointer points to: '%c' (ASCII value %d)\n", *result_ptr, (int)*result_ptr); }
/* 查找一个不存在的字符 */ printf("\n--- Searching for a character that doesn't exist ---\n"); result_ptr = strchr(str, 'z'); if (result_ptr != NULL) { printf("Character 'z' found? This is unexpected.\n"); } else { printf("Character 'z' not found, as expected. strchr returned NULL.\n"); }