c语言strcmp源代码
时间: 2023-06-23 13:44:49 浏览: 94
C语言中的strcmp函数的源代码实现如下:
```c
int strcmp(const char* str1, const char* str2)
{
while(*str1 && (*str1 == *str2))
{
str1++;
str2++;
}
return *(const unsigned char*)str1 - *(const unsigned char*)str2;
}
```
该函数使用了指针遍历字符串的方式,逐个比较两个字符串的字符,直到发现不同的字符或者遍历到字符串的结束位置为止。如果两个字符串完全相同,则返回0;否则,返回两个字符串第一个不同字符的ASCII码值之差。
需要注意的是,由于该函数会修改指针的指向,因此在调用该函数之前需要确保传入的参数指向的字符串是可读的,并且不会被修改。
相关问题
c语言strcmp函数源代码
下面是C语言中strcmp函数的源代码:
```c
int strcmp(const char *s1, const char *s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
```
该函数用于比较两个字符串s1和s2,返回值为0表示两个字符串相等,否则返回两个字符串第一个不相同字符的ASCII码差值。该函数会遍历两个字符串,直到找到第一个不相同的字符为止。
C语言通讯录源代码
以下是一个简单的C语言通讯录源代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CONTACTS 100
struct contact {
char name[50];
char phone[15];
};
struct contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void add_contact() {
if (num_contacts >= MAX_CONTACTS) {
printf("Sorry, the address book is full.\n");
return;
}
struct contact new_contact;
printf("Enter name: ");
fgets(new_contact.name, 50, stdin);
new_contact.name[strcspn(new_contact.name, "\n")] = '\0'; // remove newline character
printf("Enter phone number: ");
fgets(new_contact.phone, 15, stdin);
new_contact.phone[strcspn(new_contact.phone, "\n")] = '\0'; // remove newline character
contacts[num_contacts++] = new_contact;
printf("New contact added.\n");
}
void list_contacts() {
printf("Contact list:\n");
for (int i = 0; i < num_contacts; i++) {
printf("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
void search_contacts() {
char search_term[50];
printf("Enter search term: ");
fgets(search_term, 50, stdin);
search_term[strcspn(search_term, "\n")] = '\0'; // remove newline character
printf("Search results:\n");
for (int i = 0; i < num_contacts; i++) {
if (strstr(contacts[i].name, search_term) != NULL) {
printf("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
}
int main() {
char input[10];
while (1) {
printf("Enter command (add, list, search, or quit): ");
fgets(input, 10, stdin);
input[strcspn(input, "\n")] = '\0'; // remove newline character
if (strcmp(input, "add") == 0) {
add_contact();
} else if (strcmp(input, "list") == 0) {
list_contacts();
} else if (strcmp(input, "search") == 0) {
search_contacts();
} else if (strcmp(input, "quit") == 0) {
printf("Goodbye!\n");
return 0;
} else {
printf("Invalid command.\n");
}
}
}
```
这个程序使用结构体来存储联系人的姓名和电话号码,并提供了添加、列出、搜索和退出功能。请注意,此代码示例可能并不完美,仅供参考。