Programming C: Posts 10 – String in c
Content
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:
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 na[n-1]
, so the character of the string iss[ 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
- Write a program separate from a given string name. VD named Nguyen Thi sparkling => separation Flax
- Write a program standardized own name string. CEO:
ha noi
=>Ha Noi
.- Write the function switch 1 string to lowercase and 1 function converted to UPPERCASE.
- Write a program into a string of characters in the string and then count how many letters “of”.
- 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
- Write a program in numbers 3 number. Said the inscription describes the value of that number. Example 123 -> One hundred and twenty three.
Anh ơi trong cái “char threats[50]”. 50 là số ký tự hả anh ? Em thay bằng số 2 nhưng vẫn viết nhiều hơn bình thường.
Sme, đúng rồi, đó là giới hạn số lượng ký tự. Còn tại sao mà em gõ quá vẫn không bị thì mình cũng không rõ.
blog của a rất chi tiết và dễ hiểu. e thank
A cho e xin bài tập c với ạ!! 🙂
minh muon ghep hai mang thanh mot mang minh đã dùng hàm strcpy() but the program does not have a library press tring.h they must do so?
You do not have to use the library string.h tring.h
How to delete characters in a string. In C there is no delete function but can be removed by copying the address of the following characters overwrite the address of the previous character. For example we have a string ht = "Nguyen Van A", want to delete the character "prestige" do the following: strcpy(&ht[2],&ht[4]);
Brother he explained households with children this place I do not understand it copies override how.
You are just going to use it đk.
Theo mình hiểu thì cái lệnh strcpy(&ht[2],&ht[4]); will copy the address from ht[4] to ht[n] address from ht[2] to the end. This command will save the value override his address to, therefore it is equivalent to delete ht[2] and ht[3] old. Specifically here, it overrides the part “Van A” on phan “uyen Van A”. Such “captain” will be on top and lost.
If the override, a string “Van A” override strings “uyen Van A” , This string ko two equal lengths that so it was not the piece of string balance “uyen Van A” huh ???
Since we are used to copy address, so it's taken a new address, rather than a replacement of characters.
@trousers: you write, try to explain to people with rather, programming to understand, but what is different parrot style education Vietnam.
Up above it like you say it.
Oh there is this article a e k f vs known as a help:
Cam Caesar is back 3 characters: a->x, b->, c>from,…, from->in
input:
string s before decrypting (0<s bill is watching
a writing code in C all households e vs sir. e thank!
You browse each character, then reset each character is đk.
My ad is somewhat modern crabs c ko eh. classroom teachers up both issues
Ah in this series without you offline. I'll try to supplement.
a help e with sir…..h e now have all indicated this will by a user solve k sir….
Threads: permutation of letters printed COMPUTER, e should start direction sir…
You see it this article: https://www.cachhoc.net/2013/09/03/thuat-toan-liet-ke-hoan-vi/
he lectures about subjects not his artificial intelligence
Sorry I do not have you ah.
He said some examples of characters and content inspection for export which are not his character
Never quite know what you mean @@ Check and export?
for little children ask the meaning of this statement is what sir or what value it returns sir
with[strlen(with)-1];
access the last character of the string s.
vậy cái i– to do what was??
To reduce the variable i down 1 unit.
at the end he made the example of the handler without using how he???
in–; // why???
Sau khi xoá dấu cách ở vị trí i, thì dấu cách ở vị trí i + 1 lại đc chuyển vào vị trí i,
Nếu ta ko i–; thì sẽ bỏ qua dấu cách này, khiến ko xoá đc hết dấu cách thừa( example 3 dấu cách liền nhau thì chỉ xoá đc 1 dấu cách thôi).
Em giải thích thế đúng ko a 😀
Yeah you.
em van chua lam duoc bai nao hihu
You can visit https://chamcode.net to do offline, có hệ thống chấm đúng sai luôn 😉
He asked me how to import and print an array of many different names sir?
You declare char s[n][m] where n is the number of people, m is the number of characters max 1 name. then import each s[in] one.
This example applies only when the larger chain length 0 and no extra white sign at the top, end or between words.
em hỏi cái ạ ở bài đếm sốt ừ trong chuỗi vd:”nguyen van agency” have 3 from the way he scored his bride is only applicable when the k mark between the words white
no excess play nhé.
cho em hỏi xâu ” hoc tap ” then whitespace characters before and after “hoc tap” get the character is not you
Taking nhé.
so that transfer of the first letters to uppercase own name, use any function that you ?
DIY nhé, no content available.
darling towards solving 6 What is sir ?
This article similar to all transfers from the word. You need to separate the digits out, based on the order of their position to make appropriate reading.
he asked me why using library e ,then declare the function strcpy but the machine is required to enter the e strcpy_s Then enter the star strcpy_s still wrong sir??thank a nhieu
What do you use to code so software?
Concept of wrong sequence, string can not have children of my ad!.
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).
“nguyenvanquan7826” there is not your chain?
Code strings that count from the admin to do the above is not reasonable(in many cases input a 'space')
Above I have noted I got you: “This example applies only when the larger chain length 0 and no extra white sign at the top, end or between words.”
e nghĩ là i– used to control for each digit in the sequence only separated single 1 space
because if the user's entered more than two spaces which do not use i– it only reduced 1 only spaces eg :Nguyen Van Quan Nguyen Van Quan, the =. Where we know the user's bag drips enter spaces they can be I + 1, i + 2, i + 3,…I + n so we use I– in order to solve the problem for
How can I convert a numeric character to a number? ???
get the address of the domesticated character to the numeric string
fflush(stdin); to stop the input character from reaching the next character