0% found this document useful (0 votes)
62 views2 pages

Comparing Two Strings

This document outlines the steps to compare two strings in C: 1. Include the string library for string functions like strncmp(). 2. Declare string variables as character arrays to store the strings. 3. Choose the number of characters to compare, balancing precision with speed.

Uploaded by

Zaira Lipana
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views2 pages

Comparing Two Strings

This document outlines the steps to compare two strings in C: 1. Include the string library for string functions like strncmp(). 2. Declare string variables as character arrays to store the strings. 3. Choose the number of characters to compare, balancing precision with speed.

Uploaded by

Zaira Lipana
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Steps 1.

1
Include the string library in your program. This library contains a lot of useful functions used when working with strings, including one that compares them. Place the following code at the top of the program, with the other includes.
include <string.h>

2. 2
Declare the string variables. Those will be the strings you will compare. Note that strings in C are declared as arrays of characters, not as a special string type.
char string1[limit], string2[limit]; // Replace "limit" with the maximum length of the strings

3. 3
Decide how many characters you wish to compare. 1.

The more you compare, the higher precision you will achieve (For example, if the strings were "Hell" and "Hello" and you compared four characters, they would appear the same). If you compare a lot of characters, the comparison will be slower. There is no need to make this number greater than the strings' lengths (there are no characters to compare after their end).

4. 4
Create a variable that contains the number of characters to compare.
int compareLimit = 100; // Here, the limit is 100. However, you may change it to satisfy your needs.

5. 5
Initialize the strings. You may assign the value manually, read it from the input, read it from a file...

6. 6
Compare the strings. The comparison is done using the strncmp() function, and the returned type is an integer.
int result = strncmp(string1, string2, compareLimit);

7. 7

Examine the result. If it is positive, the first string is larger. If it is negative, the second is larger. If it is 0, they are equal.
if(result > 0) printf("string1 > string2"); else if(result < 0) printf("string2 > string1"); else printf("string1 == string2");

You might also like