learn through suffering C language learn through suffering 
C language

String manipulation functions

Conversion to numbers

C has various functions available for processing strings.
By using them effectively, you can freely manipulate strings.

The `atoi` function assigns the result of converting a string to a number to a variable.
Here's how to use the atoi function.
Please note that you need to include stdlib.h to use the atoi function.

Source code
Variable = atoi(String array name);

The following program is an example of using the atoi function to convert a number.

Source code
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[] = "145";
    int suuti = atoi(str);
    printf("%d\n", suuti);
    return 0;
}

The output of this program is as follows.

Results
145

The `atoi` function can also convert signed numbers with plus or minus signs.
If a non-numeric string is specified, it will be converted to 0.
When converting to a real number, use the atof function.It's used the same way.

String copy

You can use the `strcpy` function to copy strings.
The following is how to use the strcpy function.
Note that you need to include string.h to use the strcpy function.

Source code
strcpy(Destination string array name, Source string array name);

Originally, this function was designed for copying between string arrays.
In practice, it seems to be frequently used for string assignments.
The following program is an example of using the strcpy function to assign a string.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[10];
    strcpy(str, "MARIO");
    printf("%s\n", str);
    return 0;
}

The output of this program is as follows.

Results
MARIO

As we described the method of substitution one by one in the previous chapter, this approach is simpler.
Furthermore, there's also the `strncpy` function, which copies only the specified number of characters from the beginning.
Here's how to use the strncpy function.

Source code
strncpy(Destination string array name, Source string array name, Number of characters to copy);

This function simply copies a number of characters equal to the input length.
Sometimes, the copied string may not have an EOS at the end.
It will continue to display indefinitely if left as is, so it's essential to add EOS.

Source code
strncpy(Destination string array name, Source string array name, Number of characters to copy);
Destination string array name[Number of characters to copy] = '\0';

The following program is an example of extracting and displaying the first three characters of a string.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str1[] = "MARIO", str2[10];
    strncpy(str2, str1, 3);
    str2[3] = '\0'; /* Add EOS */
    printf("%s\n", str2);
    return 0;
}

The output of this program is as follows.

Results
MAR


strncpy is dangerous.
You must always add an EOS (End Of String) when using the `strncpy` function.
If you forget the EOS, you're going to get a bunch of irrelevant characters and an error.
You must use it with extreme caution.

String concatenation

If you're just concatenating string literals, a function isn't necessary.
Because string literals are simply concatenated when placed next to each other.
The following program demonstrates string literal concatenation.

Source code
#include <stdio.h>
int main(void)
{
    char str[] = "DRAGON""QUEST";
    printf("%s\n", str);
    return 0;
}

The output of this program is as follows.

Results
DRAGONQUEST

I think you'll see that DRAGON and QUEST are linked.

However, you cannot concatenate strings stored in an array by simply listing the array name.
In that case, you would use the `strcat` function.The following is how to use the strcat function.
Note that you need to include string.h to use the strcat function.

Source code
strcat(Array storing the original string, Array storing the string to be added);

The following program is an example of using the strcat function to concatenate strings.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str1[12] = "DRAGON";
    char str2[] = "QUEST";
    strcat(str1, str2);
    printf("%s\n", str1);
    return 0;
}

The output of this program is as follows.

Results
DRAGONQUEST

Please be careful when using this function, as the array that stores the original string...
It's only necessary to consider the length of the original string plus the string being added.
If the character array's length is insufficient, it can cause a buffer overflow error.

C is prone to bugs.
As mentioned repeatedly since the beginning of this chapter,
C is a language where using the wrong array length can cause bugs to appear in the blink of an eye.
It's a language more prone to bugs than other programming languages.

The ultimate string concatenation function

I'd like to introduce you to the ultimate string synthesis function now.
As far as the author's research indicates, this function is not introduced in most introductory texts.
This function is a versatile one that can be used for any string concatenation, so it's worth learning.

The sprintf function is similar to the printf function in that it...
In the case of the sprintf function, the result is stored within an array.
You can freely utilize the various functions of the printf function.

The following is how to use the sprintf function.
Note that you need to include stdio.h to use the sprintf function.

Source code
sprintf(Array to store results, Format string, Various variables...);

The following program is an example of using the sprintf function.

Source code
#include <stdio.h>

int main(void)
{
    char str[16];
    char str1[12] = "DRAGON";
    char str2[] = "QUEST";
    int i = 3;
    sprintf(str, "%s%s%d\n", str1, str2, i);
    printf(str);
    return 0;
}

The output of this program is as follows.

Results
DRAGONQUEST3

This function allows for most string concatenations.

Direct character array
In the previous program, we displayed the string by passing the character array `str` directly without using the `%s` specifier: `printf(str);`
Since the printf function is fundamentally designed to display strings,
it can output them without needing to explicitly use the %s specifier.
However, if a string contains a % character,
it may be mistaken for an output conversion specifier and cause incorrect behavior. In such cases, use %s.

String input

You can also use the scanf function to input strings, just like numbers.
When entering a string, use the %s specifier with the scanf function.
However, do not include & before the array name.

Reasons for not using ampersands
Actually, there is a very important reason for not using ampersands. Arrays are essentially pointers themselves, which are fundamental to the C language. Because this is a crucial concept underlying C, I will take ample time later to explain it thoroughly.

The following program is an example that displays the input string as is.

Source code
#include <stdio.h>

int main(void)
{
    char str[32];
    scanf("%s", str);
    printf("%s\n", str);
    return 0;
}

The results of this program are as follows:

Results
MARIO The string entered from the keyboard
MARIO

Now you can enter strings freely, but there are a few things to keep in mind.

One issue is that providing more input than the number of elements in the array can cause an error.
You'll experience the same phenomenon as described in Chapter 6, the fear of input errors.

To resolve this issue, specify the number of elements in the character array between % and s.
For example, if the number of elements is 32, specifying %32s will truncate any characters beyond that.
The following program is an example of string truncation.

Source code
#include <stdio.h>

int main(void)
{
    char str[32];
    scanf("%32s", str);
    printf("%s\n", str);
    return 0;
}

The results of this program are as follows:

Results
0123456789012345678901234567890123456789 The string entered from the keyboard
01234567890123456789012345678901

The string is incomplete, but we've managed to avoid the incident.

Secondly, this method doesn't allow for spaces to be entered.
This is because the space is recognized as a delimiter.
Unfortunately, this issue is difficult to resolve.

Count characters.

Counting strings isn't difficult.
It's simply a matter of counting the number of characters from the beginning of the character array until an EOS appears.
The following program is an example of displaying the number of characters in an input string.

Source code
#include <stdio.h>

int main(void)
{
    int i;

    char str[256];
    scanf("%s", str);

    for (i = 0; str[i] != '\0'; i++);

    printf("%d\n", i);

    return 0;
}

The results of this program are as follows:

Results
ABCDEF  The string entered from the keyboard
6

You might find the meaning of the for loop a little confusing.
I'm just incrementing the variable 'i' until an EOS character appears within the array elements.
The variable 'i' can increase as much as needed, and since a loop isn't necessary, I'm omitting it.

It's just tedious to have to write a `for` loop every time I need to count the characters in a string.
Therefore, a function called strlen is provided to count the number of characters in a string.
Note that you need to include string.h to use the strlen function.

Source code
Variable = strlen(Character array);

The following program is an example rewritten using the strlen function.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    int i;

    char str[256];
    scanf("%s", str);

    i = strlen(str);

    printf("%d\n", i);

    return 0;
}

The result will be the same as before.

String comparison

I suspect the following program would work well when comparing the contents of character arrays.

Source code
str1 == str2;

However, you cannot use the == operator to compare character arrays.
The specific reasons will become clear in the next chapter, but I'll briefly explain them here.
In this case, we are comparing whether the arrays are exactly the same (using the same memory),
It's not comparing the contents of the arrays.

To compare the contents of a character array, you need to compare all elements using a for loop.
The following program is an example of comparing an input string to DRAGONQUEST.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    int len, i;
    char str1[256], str2[] = "DRAGONQUEST";

    scanf("%s", str1);

    len = strlen(str2);

    for (i = 0; i < len + 1; i++) {
        if (str1[i] != str2[i]) break;
    }
    
    if (i == len + 1) {
        printf("same\n");
    } else {
        printf("Different\n");
    }

    return 0;
}

The output of this program is as follows:

Results
DRAGONQUEST The string entered from the keyboard
same


Results
ABCDEF The string entered from the keyboard
Different


Results
DRAGONQUEST3 The string entered from the keyboard
Different

Because string comparisons require the strings to be identical up to the end-of-string (EOS) marker, we compare one character longer than the length of the string being compared.
It's just tedious to write a for loop every time I need to compare strings.
Therefore, there is a function called strcmp to compare strings.
Note that you need to include string.h to use the strcmp function.

Source code
Variable = strcmp(Character array1, Character array2);

This function returns 0 if the contents of the two character arrays are the same.
The following program is an example of rewriting the previous program using the strcmp function.

Source code
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str1[256], str2[] = "DRAGONQUEST";

    scanf("%s", str1);

    if (strcmp(str1, str2) == 0) {
        printf("same\n");
    } else {
        printf("Different\n");
    }

    return 0;
}

The result will be the same as before.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.


Part 0: Program Overview

  1. What is a program?



Chapter 3: Displaying on the Screen

  1. String Display
  2. line break
  3. Practice Problem 3

Chapter 4: Displaying and Calculating Numbers

  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4


Chapter 6: Input from the Keyboard

  1. input function
  2. The fear of input
  3. Practice Problem 6



Chapter 9: Repeating a Fixed Number of Times

  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9

Chapter 10: Repeating Without Knowing the Number of Times

  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10



Chapter 13: Handling Multiple Variables at Once

  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13






Chapter 19: Dynamic Arrays

  1. Create arrays freely.
  2. Practice Problem 19

Loading comment system...