【strchr與strstr函數】在C語言中,字符串處理是常見的操作,`strchr`和`strstr`是兩個非常有用的字符串查找函數。它們分別用于查找字符或子字符串在目標字符串中的位置。以下是對這兩個函數的總結與對比。
一、函數簡介
| 函數名 | 功能說明 | 返回值 |
| `strchr` | 在字符串中查找指定字符的第一次出現的位置 | 指向該字符的指針,若未找到則返回 `NULL` |
| `strstr` | 在字符串中查找指定子字符串的第一次出現的位置 | 指向該子字符串起始位置的指針,若未找到則返回 `NULL` |
二、函數原型
- `char strchr(const char s, int c);`
- `char strstr(const char s1, const char s2);`
其中:
- `s` 是要搜索的字符串;
- `c` 是要查找的字符(以ASCII碼形式傳遞);
- `s1` 是主字符串,`s2` 是要查找的子字符串。
三、使用示例
示例1:`strchr` 的使用
```c
include
include
int main() {
char str[] = "Hello, world!";
char pos = strchr(str, 'o');
if (pos != NULL) {
printf("Found 'o' at position: %ld\n", pos - str);
} else {
printf("Not found.\n");
}
return 0;
}
```
輸出:
```
Found 'o' at position: 4
```
示例2:`strstr` 的使用
```c
include
include
int main() {
char str[] = "This is a test string.";
char sub = strstr(str, "test");
if (sub != NULL) {
printf("Found substring: %s\n", sub);
} else {
printf("Not found.\n");
}
return 0;
}
```
輸出:
```
Found substring: test string.
```
四、區別與適用場景
| 特性 | `strchr` | `strstr` |
| 查找對象 | 單個字符 | 子字符串 |
| 是否區分大小寫 | 是 | 是 |
| 是否支持通配符 | 否 | 否 |
| 適用于 | 需要查找特定字符的位置 | 需要查找某個子串是否存在或位置 |
五、注意事項
- 兩個函數都屬于標準庫函數,需包含頭文件 `
- 若傳入空字符串或無效指針,可能導致程序崩潰。
- 使用時應檢查返回值是否為 `NULL`,避免訪問無效內存。
六、總結
`strchr` 和 `strstr` 是C語言中常用的字符串處理函數,前者用于查找單個字符,后者用于查找子字符串。兩者功能不同,但都用于在字符串中進行定位操作。合理使用這些函數可以提高代碼效率,簡化字符串處理邏輯。


