Programming C: Posts 10 – String in c

At all Enter made in c we've become familiar with how to declare, entry and string in C simply. In this article we will talk more about the examples, homework chain .

1. Overview

The string is treated as an array 1 dimensions of elements of type char as characters, numbers and any special characters such as +, -, *, /, $, #,...
By convention, a sequence will be terminated by the null character (‘’ : Register turong).
Example: string "Infoworld" stored as follows:

How to store string

How to store string

2. Some declaring, initialization string

We consider the following example:

// e.g about string - code by nguyenvanquan7826
#include <stdio.h>

int main() 
{
    // khai bao chuoi co toi da 50 ky tu
    char name[50]; 
    printf("Hi, What is your name? \nMy name is: ");
    gets(name);
    printf("Hi %s, welcome to C language\n", name);

    // khoi tao chuoi ngay khi khai bao
    char myLove[] = "Nguyen Thi Lap Lanh";
    puts(myLove);

    return 0;
}

Result:

Hi, What is your name?
My name is: Nguyen Van Quan
Hi Nguyen Van Quan, welcome to C language
Nguyen Thi sparkle

In the program on, I have used the function puts to print out the string Mylove, this is also a function to output string.

As above we can see is the declaration chain or medium chain then import declaration assigning values ​​to the string just right. However we can not declare then assign values ​​as follows:

char name[50];
name = "Nguyen Van Quan"; // error

Where want to declare then assign values, we must use the string copy function strcpy in library string.h to save the values ​​as follows:

// e.g about string - code by nguyenvanquan7826
#include <stdio.h>
#include <string.h>

int main() 
{
    char name[50];
    strcpy(name, "Nguyen Van Quan");
    puts(name);

    return 0;
}

3. Some examples of strings in C

3.1 Example 1: Count the number of words in the string

Please enter a string and count the number of words in the string. VD chain “Nguyen Van Quan” have 3 from.

To do this, we see each of the characters consecutively and diverging words with spaces. Therefore this article will be provided to count the number of spaces in the string. If string 1 word, no spaces, strings 2 from there 1 spaces between 2 from that. N general is from, there will be n-1 spaces.

The next problem is how to count the spaces? Simple, It has been known as the first open string is an array of characters, so we can browse the characters turn to examining the chain of characters are spaces. But want to browse all the characters in the string (character array) they must know the number of characters in the string (number of elements in the array).

Fortunately, in the library string.h we have a function to get the length of the string as a function strlen. (str – string, only – length).

// e.g about string - code by nguyenvanquan7826
#include <stdio.h>
#include <string.h> // for strlen function

int main() 
{
    char s[50];
    printf("Enter a string: ");
    gets(s);

    int i, count = 0; // count - bien dem so luong dau cach
    for (i = 0; i < strlen(s); i++ )
    {
        if(s[i] == ' ') 
        {
            count++;
        }
    }

    printf("Number word in string is: %d\n", count + 1 );

    return 0;
}

Pretty simple code, you read, understand and test nhé.

Yet we have a code on the note:

  • To represent characters, then we put the apostrophe pair, then we put the string in quotes. Should the above spaces enclosed in single quotes and we can compare 2 characters with such comparisons with 2 number, still 2 chains can not compare so, You can read more about comparing strings.
  • Because the string is an array of characters, should like to take ith character in the string s, then we as the array access is s[in].
  • This example applies only when the larger chain length 0 and no extra white sign at the top, end or between words.
  • Like loops above, we have conditions i < strlen(s), however the nature of a loop strlen again to count the number of characters of the string s. So if we write directly on the conditions in each iteration, program must run the command loop strlen to count the number of characters of s. This is redundant and make the program run longer. So we will put 1 variable is the length of the string out as follows:
int len = strlen(s);
for (i = 0; i < len; i++ )
{
    if(s[i] == ' ') 
    {
        count++;
    }
}

3.2 Example 2: Standardize the string

Please enter a string and remove all extra spaces at the top, Last and between words if.

This problem is important for the problem of software, later when stored, Input data is noteworthy to be standardized, no surplus or deficit caused errors in the process and seek.

  • The first character of the string s is space, then s[0] the spaces, we delete it as done.
  • The characters between words if redundant ie s[in] and s[i 1] along the spaces. We removed 1 in 2 is ok, because the words will separated by 1 spaces should have retained 1 spaces.
  • The characters at the end string is space, then we will remove it by assigning the last character is a null character '\0' is finished. Remember that the last character is the element of the array n a[n-1], so the character of the string is s[ strlen(s) - 1 ].

The next problem is how to delete 1 characters in the string? You look at the example above we use the string copy function, and to delete 1 or a number of characters in the string we will use this function, but will be used in the copy address.

To delete a character from i to j characters in the string s, we command strcpy(&s[i], &s[j+1]);. The essence is that we copy the address of s[j+1] the address of s[i].

// e.g about string - code by nguyenvanquan7826
#include <stdio.h>
#include <string.h>

int main() 
{
    char s[50];
    printf("Enter a string: ");
    gets(s);

    // delete all space at start of string
    while( s[0] == ' ' ) strcpy(&s[0], &s[1]);

    // delete all space at end of string
    while( s[ strlen(s)-1 ] == ' ') s[ strlen(s)-1 ] = '\0';

    // delete all space between two word 

    int i;
    for(i = 0; i < strlen(s); i++)
    {
        if( s[i] == ' ' && s[i+1] == ' ')
        {
            strcpy(&s[i], &s[i+1]);
            i--; // why???
        }
    }

    printf("s=%s.\n", s);

    return 0;
}

Ok. You run nhé. Remember enter the string excess space at the beginning, final, between to check.

A small question as exercises do more for you is to look at the code line i--; // why??? and think why this line? Why do i have to decrease 1?

4. Some functions on strings and characters

The test function symbols. (these functions in a library ctype.h) If true, the function for different values 0. If false, the function value by 0.

  • Int isalpha(int c) : check the alphabetical characters are not.
  • Int isdigit(int c) : check digit character is not.
  • Int islower(int c): check lowercase characters are not.
  • Int isupper(int c): check uppercase characters are not.
  • Int iSPACE(int c): check character is empty (\n, spaces, \t).

The string processing functions. (This function is located in the library string.h)

  • Int strlen(char * s) returns the length of the string s;
  • Char * strupr(char * s) Change in lowercase to uppercase string s.
  • Char * strlwr(char * s) Change uppercase to lowercase.
  • Char * strcat(char * s1, char * s2) connection string to string s1 s2;
  • Int strcmp(char * s1, char * s2) the negative value if the strings s1 and smaller string s2. And for the price refugee positive if greater string strings s1 s2. Returns the value of 0 if the string s1 with the string s2.
  • Int strcmpi (char * s1, char * s2) compare 2 string but do not distinguish lowercase and uppercase.
  • Char * strcpy(char * s1, char * s2) copy string to string s1 s2.
  • Char * strncpy(char * s1, char * s2, int n) Copy the first n characters of string s2 to string s1
  • Char * strnset(char * s ,int c, int n) n times to copy the character c in string s.
  • Char * strstr(char * s1, char * s2) look for the occurrence of the string s2 in the string s1. If you find the address of the function substring in string s1. In contrast to NULL.
  • Char * strrev(char * s) Using reverse s.Neu successful string functions to address string reversed.

Exercise

  1. Write a program separate from a given string name. VD named Nguyen Thi sparkling => separation Flax
  2. Write a program standardized own name string. CEO:ha noi => Ha Noi.
  3. Write the function switch 1 string to lowercase and 1 function converted to UPPERCASE.
  4. Write a program into a string of characters in the string and then count how many letters “of”.
  5. Write a program on a string. Check if it is mirrored string? Symmetry is the string string when writing backwards and still like the original string. CEO level
  6. Write a program in numbers 3 number. Said the inscription describes the value of that number. Example 123 -> One hundred and twenty three.