Strings in C
Strings
We have seen arrays and multidimensional arrays. What we call a "string" is actually an array. Arrays with the data type char
(characters) are called strings or "strings" in English.
Strings do not differ from arrays in terms of functionality. For example, in an integer array (int
), we store integers; in a character array (a string), we store characters. There is no fundamental difference. However, because they are frequently used, strings deserve special attention. If your operations are not scientific or computation-heavy, regardless of which language you use, the most common type of array you will interact with is the character array. We use character arrays for things like names, addresses, usernames, phone numbers, and anything else that can be expressed in words. This is why strings are important!
In English, these are called "Strings", meaning something like a cord or rope. I don't know who first decided on the name "string", but it probably relates to how characters are stored consecutively in memory cells, which might have been compared to wagons of a train. The Turkish word katar (meaning "train" in Arabic) might have been chosen because of this resemblance. A more appropriate name could have been used, or we could just have called it a "character array". But since there's a commonly accepted term, we’ll stick with it in this article. "String", "katar", or "character array" are all the same thing: an array with character type elements.
Using printf()
and scanf()
with Strings
We mentioned that strings are essentially just arrays, but there are a few practical differences. In the case of arrays, we need to manually assign values to each element or read them one by one using scanf()
or printf()
. However, for strings, this isn’t necessary. You can read a word with a single scanf()
call, and the assignment of values to the elements happens automatically. For example, if the input is "Merhaba" (meaning "Hello"), the 3rd element of the array will be 'r', and the 6th element will be 'b'. Unlike other arrays where you have to assign values step by step, strings handle this automatically.
Here’s an example:
#include<stdio.h>
int main(void) {
char name[30];
printf("Enter a name> ");
scanf("%s", name);
printf("Your name: %s\n", name);
return 0;
}
In this example, we define a character array with 30 elements to store the name. The maximum length of the string that can be stored is 29 characters, because one extra cell is reserved for the null character ('\0'
) that indicates the end of the string.
Notice that with strings, when using scanf()
, you don’t need to use the address-of operator (&
) as you would with other arrays. This is because scanf()
knows that it should start at the first address of the string and read characters sequentially.
Now, let’s modify the program slightly to print each character one by one, instead of using printf()
directly:
#include<stdio.h>
int main(void) {
char name[30];
int i;
printf("Enter a name> ");
scanf("%s", name);
printf("Your name: ");
for(i = 0; name[i] != '\0'; i++)
printf("%c", name[i]);
printf("\n");
return 0;
}
Here, we use a for
loop to print each character individually. The condition name[i] != '\0'
ensures that we stop printing when the null character ('\0'
) is encountered, signaling the end of the string.
Using gets()
and puts()
If you want to read a sentence containing spaces, the scanf()
function will only take the first word before the space. To read a sentence with spaces, we can use gets()
to read the entire line and puts()
to print it. For example:
#include<stdio.h>
int main(void) {
char sentence[40];
printf("Enter a sentence> ");
gets(sentence);
printf("You entered:\n");
puts(sentence);
return 0;
}
The gets()
function reads everything until the Enter key is pressed, including spaces. The puts()
function prints the string, adding a newline (\n
) at the end. However, gets()
has a security risk as it does not check for buffer overflows, so it's better to use fgets()
in modern code.
Initializing Strings
When you declare a string, all its elements are automatically initialized to '\0'
. However, you can also initialize the string with a specific value in two ways:
Method 1:
#include<stdio.h>
int main(void) {
char name[] = "CAGATAY";
printf("%s\n", name);
return 0;
}
Method 2:
#include<stdio.h>
int main(void) {
char name[] = {'C', 'A', 'G', 'A', 'T', 'A', 'Y', '\0'};
printf("%s\n", name);
return 0;
}
In Method 1, the string is initialized directly with a literal, while in Method 2, you assign characters one by one and explicitly add the null character at the end.
Formatted Output for Strings
Just like with numeric values, strings can be printed in a formatted way using printf()
. Here's an example of how you can control the width and alignment of the string:
#include<stdio.h>
int main(void) {
char sentence[20] = "Testing";
// Print normally:
printf("%s\n", sentence);
// Right-align with a width of 20 characters:
printf("%20s\n", sentence);
// Print only the first 5 characters, right-aligned:
printf("%20.5s\n", sentence);
// Left-align the string with a width of 20 characters:
printf("%-20s\n", sentence);
return 0;
}
In this example:
-
%20s
right-aligns the string in a space of 20 characters. -
%.5s
prints only the first 5 characters of the string. -
%20.5s
right-aligns the first 5 characters within a 20-character space. -
%-20s
left-aligns the string in a space of 20 characters.
Standard String Functions
The C Standard Library provides several functions to work with strings. These are included in the string.h
header file.
-
strlen()
returns the length of the string (not counting the null terminator). -
strcpy()
copies a string into another. -
strcmp()
compares two strings lexicographically. -
strcat()
concatenates two strings.
For example, here is how to use strlen()
:
#include<stdio.h>
#include<string.h>
int main(void) {
printf("String length: %d\n", strlen("Hello"));
return 0;
}
Command-Line Arguments
The main()
function can also accept arguments passed from the command line. This allows you to pass values to your program when you run it.
Here’s an example:
#include<stdio.h>
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%d. argument: %s\n", i, argv[i]);
}
return 0;
}
If you compile and run the program like this:
$ ./program_name arg1 arg2 arg3
The program will print all the arguments passed to it, including the program’s name itself (argv[0]
).
Yorumlar
Yorum Gönder