> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/piscine-life/c03/ft_strncmp.md).

# ft\_strncmp

**Objective:**

Recreate the behavior of the `strncmp` function (refer to `man strncmp`).

**Turn-in Directory: `ex01/`**

**Files to Turn In: `ft_strncmp.c`**

**Allowed Functions: None**

**Prototype:**

```c
int ft_strncmp(char *s1, char *s2, unsigned int n);
```

***

#### **Detailed Explanation:**

**1. Functionality:**

The `ft_strncmp` function compares the first `n` characters of two strings, `s1` and `s2`. It returns:

* `0` if the strings are equal (up to `n` characters).
* A positive value if `s1` is greater than `s2`.
* A negative value if `s1` is less than `s2`.

**2. Input Parameters:**

* `char *s1`: A pointer to the first string to be compared.
* `char *s2`: A pointer to the second string to be compared.
* `unsigned int n`: The maximum number of characters to compare.

**3. Output:**

* Returns `0` if the strings are equal (up to `n` characters).
* Returns a positive or negative value based on the difference between the first differing characters.

***

#### **Steps to Implement:**

1. **Check if `n` is 0:**
   * If `n` is 0, the function immediately returns `0` because no characters need to be compared.
2. **Initialize a Counter:**
   * Use a counter `i` to iterate through the characters of `s1` and `s2`.
3. **Compare Characters:**
   * Use a `while` loop to compare characters of `s1` and `s2` until:
     * The characters differ.
     * The end of either string is reached (`\0`).
     * The maximum number of characters (`n - 1`) has been compared.
4. **Check for Equality:**
   * If the loop ends and the characters are still equal, return `0`.
5. **Return the Difference:**
   * If the characters differ, return the difference between the ASCII values of the differing characters.

***

#### **Code Explanation:**

```c
int ft_strncmp(char *s1, char *s2, unsigned int n)
{
	unsigned int	i;

	// If n is 0, no comparison is needed, return 0 immediately
	if (n == 0)
		return (0);

	// Initialize the counter
	i = 0;

	// Loop through the strings while:
	// 1. The characters are equal
	// 2. The end of s1 is not reached
	// 3. The maximum number of characters (n - 1) has not been compared
	while (s1[i] == s2[i] && s1[i] != '\0' && i < n - 1)
		i++;

	// After the loop, check if the characters are still equal
	if (s1[i] == s2[i])
		return (0); // If equal, return 0
	else
		return (s1[i] - s2[i]); // If not equal, return the difference
}
```

***

#### **Step-by-Step Breakdown:**

1. **Check if `n` is 0:**
   * If `n` is 0, the function immediately returns `0` because no comparison is needed.
2. **Initialize the Counter:**
   * `unsigned int i = 0;`
   * The variable `i` is used to iterate through the characters of `s1` and `s2`.
3. **Compare Characters:**
   * The `while` loop continues as long as:
     * `s1[i] == s2[i]`: The characters at position `i` in `s1` and `s2` are equal.
     * `s1[i] != '\0'`: The end of `s1` has not been reached.
     * `i < n - 1`: The maximum number of characters (`n - 1`) has not been compared.
4. **Check for Equality After the Loop:**
   * If the loop ends and `s1[i] == s2[i]`, the strings are equal (up to `n` characters), so return `0`.
5. **Return the Difference:**
   * If the characters differ, return the difference between `s1[i]` and `s2[i]` (`s1[i] - s2[i]`).

***

#### **Example Usage:**

```c
#include <stdio.h>

int ft_strncmp(char *s1, char *s2, unsigned int n);

int main(void)
{
	char s1[] = "Hello, 42!";
	char s2[] = "Hello, World!";
	unsigned int n = 7;

	int result = ft_strncmp(s1, s2, n);

	if (result == 0)
		printf("The first %d characters are equal.\n", n);
	else if (result > 0)
		printf("s1 is greater than s2.\n");
	else
		printf("s1 is less than s2.\n");

	return (0);
}
```

**Expected Output:**

Copy

```sh
The first 7 characters are equal.
```

***

#### **Edge Cases to Test:**

1. **Empty Strings:**
   * Input: `s1 = ""`, `s2 = ""`, `n = 5`
   * Expected Output: `0` (equal)
2. **Partial Comparison:**
   * Input: `s1 = "Hello"`, `s2 = "Helloo"`, `n = 5`
   * Expected Output: `0` (equal up to `n` characters)
3. **Strings Differ Before `n`:**
   * Input: `s1 = "Hello"`, `s2 = "Hella"`, `n = 5`
   * Expected Output: Positive value (`'o' - 'a'`)
4. **`n` is 0:**
   * Input: `s1 = "Hello"`, `s2 = "World"`, `n = 0`
   * Expected Output: `0` (no comparison)
5. **Strings with Special Characters:**
   * Input: `s1 = "Hello\n42!"`, `s2 = "Hello\nWorld!"`, `n = 10`
   * Expected Output: Negative value (`'4' - 'W'`)

***

#### **Limitations of `ft_strncmp`:**

* The function does not handle `NULL` pointers. Passing `NULL` will result in undefined behavior.
* The function assumes valid strings (null-terminated). Non-null-terminated strings may cause unexpected behavior.

<br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/piscine-life/c03/ft_strncmp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
