STRINGS IN C PROGRAMMING LANGUAGE
A string in the C language represents an array of char type data and is used for working with text. They are defined as follows:
char text[ ]="This is some text";
or, it can be like this:
char text[]={'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 's', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '\0'};
Data type char
The char data type is similar to the int data type, ie. is used to describe integers, but only occupies 8 bits of memory, unlike int, which occupies 16 or 32 bits and can store a larger number.
The char type is usually used to store character data, i.e. their codes.
So, for example, if we want to store the letter A in memory, we would actually store the code of the letter A. The character(s) codes are associated numbers, with which we distinguish the character.
For example. for the letter A, the number is 65, for the letter B, it is 66, etc. We can get the value of the code if we put the character under apostrophes. eg 'A'.
An example of defining the code of the letter A and printing it, along with printing the character would be:
The char type is usually used to store character data, i.e. their codes.
So, for example, if we want to store the letter A in memory, we would actually store the code of the letter A. The character(s) codes are associated numbers, with which we distinguish the character.
For example. for the letter A, the number is 65, for the letter B, it is 66, etc. We can get the value of the code if we put the character under apostrophes. eg 'A'.
An example of defining the code of the letter A and printing it, along with printing the character would be:
char ch='A';
printf("Letter code and letter: %c %d\n",ch,ch);
printf("Letter code and letter: %c %d\n",ch,ch);
After starting:
Example 1: Print a table of ASCII character codes
We will print the character codes by using the for loop to change the codes from 32 to 126 and print those values using the conversion "%c" to print the character, and "%d" to print the code of the corresponding character.
Note: Code 127 and codes 0-32 exist and refer to non-printing characters, control and whitespace characters. There are also signs with codes greater than 127 and less than or equal to 255 and they depend on local settings. For example. Cyrillic letters in certain areas, etc.
Note: Code 127 and codes 0-32 exist and refer to non-printing characters, control and whitespace characters. There are also signs with codes greater than 127 and less than or equal to 255 and they depend on local settings. For example. Cyrillic letters in certain areas, etc.
#include < stdio.h >
#include < stdlib.h >
int main()
{
#include < stdlib.h >
int main()
{
for(int ch=32;ch <= 126;ch++){
return 0;
}
printf("%c %d\n",ch,ch);
}return 0;
After executing the program we see the following:
Enter characters from the keyboard
Input of one character from the keyboard, including the white character, can be done using the getchar() function from the <stdio.h> header.
In the same header, there is also a function that will print this character, putchar(ch), where ch is that character.
In the same header, there is also a function that will print this character, putchar(ch), where ch is that character.
Character testing using functions from the <ctype.h> header
If we want to examine the type of character that was entered, we can use the functions from the <ctype.h> header
Some functions from the header "ctype.h"
- isalnum(ch), Is "ch" a letter or a digit?
- isalpha(ch), Is "ch" a letter?
- islower(ch), Is "ch" a lowercase letter?
- isupper(ch), Is "ch" a uppercase letter?
- isdigit(ch), Is "ch" a decimal digit?
- isspace(ch), Is "ch" a white space character?
- ispunct(ch), Is "ch" a special character (punctuation mark)?
- iscntrl(ch), Is "ch" a control character?
Example 2: Analysis of the entered code
Create a program that requires the user to enter a code and prints on the screen how many lowercase, uppercase letters, numbers and punctuation marks in that code.
To enter the code, we will use the do-while loop and the getchar() function, to enter character by character, and the functions from the <ctype.h> header, to check the character type. The code is shown below:
#include < stdio.h >
#include < ctype.h >
int main()
{
#include < ctype.h >
int main()
{
int sc=0;//number of punctuation marks
int nd=0;//number of digits
int uc=0;//number of uppercase letters
int lc=0;//number of lowercase letters
char ch;
printf("Enter the password!\n");
do{
printf("The code has %d lowercase letters, %d uppercase letters, %d digit(s) and %d special
characters.\n",lc,uc,nd,sc);
return 0;
}
int nd=0;//number of digits
int uc=0;//number of uppercase letters
int lc=0;//number of lowercase letters
char ch;
printf("Enter the password!\n");
do{
ch=getchar();
if(ispunct(ch)){
if(isdigit(ch)){
if(isupper(ch)){
if(islower(ch)){
}
while(ch!=EOF && (!isspace(ch) && !iscntrl(ch)));if(ispunct(ch)){
sc++;
}if(isdigit(ch)){
nd++;
}if(isupper(ch)){
uc++;
}if(islower(ch)){
lc++;
}printf("The code has %d lowercase letters, %d uppercase letters, %d digit(s) and %d special
characters.\n",lc,uc,nd,sc);
return 0;
Input is carried out until a white-space character or a control character is read, e.g. new line, or until the end-of-file character is read (ctrl+Z).
The execution of the previous example can be seen in the following picture:
The execution of the previous example can be seen in the following picture:
Strings and pointers
Strings in the C language represent strings of char type data that can also be created dynamically, i.e. using pointers.
Let's define two strings as follows:
Let's define two strings as follows:
char* pText = "Today is a beautiful day";
char text2[30] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
char text2[30] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
The first one is defined by a pointer (dynamic) and the second string is a static string of char type data. Both strings are initialized with an array of characters, in two different ways, but in both cases the arrays of characters terminated by the '\0' character is obtained.
Through a loop, for example while, we can move the pointer one place at a time and use the operator(*) to "get" the character pointed to by that pointer, and then print the character using the printf command.
A pointer points to a specific array element and if we want to change the pointer to point to the next element, we can do so simply by incrementing the pointer value, e.g. if we write:
pText++;
This is well explained in the following article: www.scaler.com/topics/c/string-pointer-in-c/
To have a pointer to another string we will add the following line:
Through a loop, for example while, we can move the pointer one place at a time and use the operator(*) to "get" the character pointed to by that pointer, and then print the character using the printf command.
A pointer points to a specific array element and if we want to change the pointer to point to the next element, we can do so simply by incrementing the pointer value, e.g. if we write:
pText++;
This is well explained in the following article: www.scaler.com/topics/c/string-pointer-in-c/
To have a pointer to another string we will add the following line:
char* pch2 = text2;//pointer psh2 points to the first element of the text2 array
The complete code is given below:
#include < stdio.h >
int main()
{
int main()
{
char* pText = "Today is a beautiful day";
char text2[30] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
printf("Text 1:\t");
while (*pText != '\0')
{
printf("\n");
char* pch2 = text2;//pointer psh2 points to the first element of the text2 array
printf("Text 2:\t");
while(*pch2 != '\0')
{
printf("\n");
return 0;
}
char text2[30] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
printf("Text 1:\t");
while (*pText != '\0')
{
printf("%c", *pText);
pText++;
}pText++;
printf("\n");
char* pch2 = text2;//pointer psh2 points to the first element of the text2 array
printf("Text 2:\t");
while(*pch2 != '\0')
{
printf("%c",*pch2);
pch2++;
}pch2++;
printf("\n");
return 0;
The cycle is terminated when the character '\0' is encountered.
After running the program you can see the following:
After running the program you can see the following:
String input in the C language
String input can be done, in addition to loading it with getchar(), character by character, as shown in the previous example and using the scanf command, to load the text up to the whitespace character, as follows:
char word[10];
scanf("%s",&word);
scanf("%s",&word);
To load the entire line of text up to the newline character, the gets(text) function can be used, and to print the loaded line, the puts(text) function from the <stdio.h> header can be used. The following example shows the loading of text, in some of the mentioned ways.
Example 3: Entering a string
Enter two strings from the standard input, the first so that loading is done up to a white character (one word), and for entering the second, the entire line of text is read, up to the newline character.
The code is shown below:
The code is shown below:
#include < stdio.h >
#include < stlib.h >
int main()
{
#include < stlib.h >
int main()
{
char text1[10],text2[10];
//Input with the scanf function up to a white character
printf("Enter the first text!\n");
scanf("%s",text1);
printf("%s",text1);
getchar();//takes 1 character
//input character by character
printf("\nEnter the second text!\n");
gets(text2);
puts(text2);
printf("%s",text2);
return 0;
}
printf("Enter the first text!\n");
scanf("%s",text1);
printf("%s",text1);
getchar();//takes 1 character
//input character by character
printf("\nEnter the second text!\n");
gets(text2);
puts(text2);
printf("%s",text2);
return 0;
Determining the length of the text
The length of the text can be determined with the strlen() function from the <string.h> header
char text[]="Preparation for the programming competition";
int length=strlen(text);
printf("The length of the text is %d\n",length);
int length=strlen(text);
printf("The length of the text is %d\n",length);
Extracting part of text from text (Extracting substring)
A part of the text can be extracted from the whole text, by using a loop to go through the array of char data, from the position in the text where the substring should be extracted, until the final desired position and by adding the current character to the new string of char data, i.e. into a substring.
This is demonstrated in the following example:
This is demonstrated in the following example:
Example 4: Extracting a substring
Let the given text be: "Preparation for the programming competition". Extract part of the text from position 12, length 10
characters and print on the screen.
characters and print on the screen.
Solution: You should start from the given text, then create a loop and set the control variable "c" to an initial value equal to the initial position of the desired substring. The code is shown below:
#include < stdio.h >
#include < string.h >
int main()
{
#include < string.h >
int main()
{
char text[]="Preparation for the programming competition";
int length=strlen(text);
int pos=20; //the substring starts at position 20
int lenSubstr=11;
char substring[length];
for(int c = pos,i=0;c <= pos+lenSubstr;c++,i++){
printf(substring);
return 0;
}
int length=strlen(text);
int pos=20; //the substring starts at position 20
int lenSubstr=11;
char substring[length];
for(int c = pos,i=0;c <= pos+lenSubstr;c++,i++){
char ch= text[c];
substring[i]=ch;
}substring[i]=ch;
printf(substring);
return 0;
Position "c" represents the position of the current character within the given text, and "i" is the position of the current element in the array of chars that represents the requested substring. While the position "c" starts from the value of the variable pos, the position "i" starts from the value zero.
The task can be solved in another way, using the strcpy() function from the <string.h> header.
This function copies a part of one string to another, which is less than or equal in length to the first one.
Other functions from the <string.h> header can be viewed at the following website: cplusplus.com/reference/cstring/
The code is shown below:
This function copies a part of one string to another, which is less than or equal in length to the first one.
Other functions from the <string.h> header can be viewed at the following website: cplusplus.com/reference/cstring/
The code is shown below:
#include < stdio.h >
#include < string.h >
int main()
{
#include < string.h >
int main()
{
char tekst[]="Preparation for the programming competition";
int length=strlen(text);
int pos=20; //the substring starts at position 20
int lenSubstr=11;
char substring[length];
strncpy(podstring,text+pos,lenSubstr);
printf(substring);
return 0;
}
int length=strlen(text);
int pos=20; //the substring starts at position 20
int lenSubstr=11;
char substring[length];
strncpy(podstring,text+pos,lenSubstr);
printf(substring);
return 0;
The first parameter of the strcpy() function is the substring to be obtained (destination), the second is a pointer to the character from the source text (source) at position "pos", while the third parameter is the length of the substring.
After launch:
After launch:
Search for a part of text within a larger text
It is often necessary to examine whether a certain word or text is found in the given text and, if so, to find it in which positions. The following example shows one way to do this.
Example 5: String search
Check whether and in which positions the given words ("bees" and "train") are found in the given text.
Write how many times they are repeated and in which positions if they are found or write "did not appear" if the word is not found in the text.
Write how many times they are repeated and in which positions if they are found or write "did not appear" if the word is not found in the text.
Solution: One way is by using a linear search, which involves going through the entire text, character by character and comparing the current character with the first character in the word being searched for. If a character is encountered that is the same as the first character of the search word, then the other characters of that word are checked. If the other characters of that word are the same as the current character from the text, it is stated that the word has been found, and the position from where the substring (word) begins to appear within the text is stated. In the continuation of the search through the text, the examination continues, from the position one more than the last one recorded.
The code is shown below:
The code is shown below:
#include < stdio.h >
#include < string.h >
int main()
{
#include < string.h >
int main()
{
char text2[30] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
char word1[] = "bees";
int lenText = strlen(text);
int lenWord = strlen(word1);
int pos1 = -1;//If this value remains, it means that the word was not found
int found= 0;//logical variable that indicates when the first character of the string being searched for matches the current character
int numOccurr = 0;
for(int i = 0,j = 0; i < lenText; i++){
if(numOccurr>0){
else{
return 0;
}
int lenText = strlen(text);
int lenWord = strlen(word1);
int pos1 = -1;//If this value remains, it means that the word was not found
int found= 0;//logical variable that indicates when the first character of the string being searched for matches the current character
int numOccurr = 0;
for(int i = 0,j = 0; i < lenText; i++){
char chT = text[i];
char ch = word1[j];
if(!found&& chT != ch){/* the current character in the text has not yet been matched with the first character of the searched word */
else if(!found && chT == ch){ /* Encountering a match of the first character of the string being searched for with the current character*/
}char ch = word1[j];
if(!found&& chT != ch){/* the current character in the text has not yet been matched with the first character of the searched word */
continue;
}else if(!found && chT == ch){ /* Encountering a match of the first character of the string being searched for with the current character*/
found=1;
pos1=i;
/* After finding a match for the first letter of the searched word, the examination continues to see if the rest are the same */
while(chT == ch && i < lenText && j < lenWord)
{
if(j == lenWord){/* all the letters of the searched word were equal to the characters of the text,
// so the word was found */
else{
}pos1=i;
/* After finding a match for the first letter of the searched word, the examination continues to see if the rest are the same */
while(chT == ch && i < lenText && j < lenWord)
{
i++;
j++;
chT = text[i];/*character from the source text*/
ch = word1[j];/* A character from the search word */
}j++;
chT = text[i];/*character from the source text*/
ch = word1[j];/* A character from the search word */
if(j == lenWord){/* all the letters of the searched word were equal to the characters of the text,
// so the word was found */
found=0;/* continuing the search from the last found position, we search as at the beginning,
// therefore, the first letter was not found. */
j=0;
numOccurr++;
printf("Found on %d position\n"\n",pos1);
}// therefore, the first letter was not found. */
j=0;
numOccurr++;
printf("Found on %d position\n"\n",pos1);
else{
found= 0;
j = 0;
}j = 0;
if(numOccurr>0){
printf("The word appeared %d times in the text\n",brPoj);
}else{
printf("Nope");
}return 0;
In the previous code it can be seen that the search was performed for the word "bees" and not for "train".
Below is the code that is sorted and searches for both words. These words are put into a two-dimensional array of chars:
Below is the code that is sorted and searches for both words. These words are put into a two-dimensional array of chars:
char word[2][10] = {"bees", "train"};
In the improved code, a special search function was created, which receives as parameters the position from which to start the search, the search text and the word (substring) to be searched for, and returns the value of the position of the found word or "-1" if the word is not found.
The code is given below:
The code is given below:
#include < stdio.h >
#include < string.h >
int positionInText(int pos, char txt[], char word[])
{
int main()
{
#include < string.h >
int positionInText(int pos, char txt[], char word[])
{
int lenTexta=strlen(txt);
int lenWord = strlen(word);
int found = 0;
for(int i = pos+1, j=0; i < lenText; i++)
{
if(found == 0)
{
return pos;
}
int lenWord = strlen(word);
int found = 0;
for(int i = pos+1, j=0; i < lenText; i++)
{
char chT = txt[i];
char ch = word[j];
if(!found&& chT != ch)
{
else if(!found && chT == ch)
{
}char ch = word[j];
if(!found&& chT != ch)
{
continue;
}else if(!found && chT == ch)
{
found = 1;
pos = i;
while(chT == ch && i < lenText && j < lenWord)
{
if(j == lenWord)
{
else
{
}pos = i;
while(chT == ch && i < lenText && j < lenWord)
{
i++;
j++;
chT = txt[i];
ch = word[j];
}j++;
chT = txt[i];
ch = word[j];
if(j == lenWord)
{
break;
}else
{
found =0;
j=0;
if(i >= lenText){/* the last letter was also examined, and no new match was found */
}j=0;
if(i >= lenText){/* the last letter was also examined, and no new match was found */
pos=-1;
break;
}
break;
if(found == 0)
{
pos=-1;
}return pos;
int main()
{
char text[ ] = {'E', 'v', 'a', ',', ' ', 'c', 'a', 'n', ' ', 'I', ' ', 's', 'e', 'e', ' ', 'b', 'e', 'e', 's', ' ', 'i', 'n', ' ', 'a', ' ', 'c', 'a', 'v', 'e', '\0'};
char word[2][10]= {"bees", "train"};
int numOccurr = 0;
int pos=-1;
for(int i = 0; i < 2; i++)
{
return 0;
}
int numOccurr = 0;
int pos=-1;
for(int i = 0; i < 2; i++)
{
do
{
while(pos != -1);
if(numOccurr > 0)
{
else
{
numOccurr =0;
}{
pos = positionInText(pos,text,word[i]);
if(pos != -1)
{
}if(pos != -1)
{
numOccurr ++;
printf("The word %s found on %d position\n",word[i],pos);
}printf("The word %s found on %d position\n",word[i],pos);
while(pos != -1);
if(numOccurr > 0)
{
printf("The word %s appeared %d times in the text\n",word[i],numOccurr );
}else
{
printf("The word %s did not appear in the text at all\n",word[i]);
}numOccurr =0;
return 0;
After executing the program:
In the main function a two-dimensional string of characters with search words is given and defined, the search text, the starting position initialized to -1 and the number of occurrences, whose initial value is zero.
In the do-while loop, the positionInTextu() function is called, which is passed as parameters position, text, and the search word, and it returns the first position greater than the previously found one, at which the found word is located, or -1, if the word not found in the text.
In the do-while loop, the positionInTextu() function is called, which is passed as parameters position, text, and the search word, and it returns the first position greater than the previously found one, at which the found word is located, or -1, if the word not found in the text.
Previous
|< Strings in C/C++ |
Next
Pointers in C/C++ >| |