Understanding C++ Strings
A string is a collection of characters, whether in the form of letters, numbers, spaces or other characters. In C++ string values must be enclosed in single quotes ("_").
Strings can be declared using character arrays as follows:
char var_name[N];
1. Entering String Data From Keyboard
Once a string variable is defined, we can fill in the data directly or from the keyboard using the cin function.
Example program:
#include <iostream.h>
#include <conio.h>
void main() {
char teks[13];
clrscr();
cout << "Masukkan sebuah kata ";
cin >> teks;
cout << "Yang Anda Masukkan : " << teks << endl;
getch();
}
Output:
Enter a word Assalamu'alaikum
What you entered: Assalamu'alaikum
The cin function does not accept spaces, if you enter a character that contains spaces, the following characters will not be saved. To solve this problem, add the following function:
cin.get(var, length)
//atau
cin.getline(var, length)
The above program can be modified as follows:
#include <iostream.h>
#include <conio.h>
void main() {
char teks[13];
clrscr();
cout << "Masukkan sebuah kata ";
cin.get(teks, 13);
cout << "Yang Anda Masukkan : " << teks << endl;
getch();
}
Output:
Enter a word Hello World
What you entered: Hello World
In addition, you can also use the gets(var) function from the stdio.h prototype.
2. String Manipulation Functions
Borland C++ provides several types of functions used for string manipulation. Here are some functions for string manipulation:
| Fungsi | File Header | Keterangan |
|----------|-------------------|--------------------------------------------------------------------------------------------------------------|
| strcpy() | String.h | digunakan untuk menyalin string dari variabel asal ke tujuan syntax: strcpy(tujuan, asal) |
| strlen() | String.h | digunakan untuk mengetahui jumlah karakter dalam string syntax: strlen(string) |
| strrev() | String.h | digunakan utuk membalik letak urutan string syntax: strrev(string) |
| strcat() | String.h, ctype.h | Digunakan untuk menambahkan string sumber ke bagian akhir dari string tujuan. Syntax: Strcat(tujuan, sumber) |
| strcmp() | String.h | Digunakan untuk membandingkan string pertama dan string kedua Syntax: Strcmp(str1, str2) |
Example program:
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#define MAX 30
void main() {
char str1[MAX], str2[MAX];
cout << "Masukkan sembarang kalimat : ";
gets(str1);
strcpy(str2, str1);
cout << "strcpy test : " << endl;
cout << "str1 : " << str1 << endl;
cout << "str2 : " << str2 << endl;
cout << "\n\nstrlen test : " << endl;
cout << "panjang teks : " << strlen(str2);
cout << "\n\nstrrev test : " << endl;
cout << "teks terbalik : " << strrev(str2);
getch();
}
Output:
Enter any sentence: Hello Borland C++
strcpy test :
str1 : Hello Borland C++
str2 : Hello Borland C++
strlen test :
text length : 17
strrev test :
reverse text : ++C dnalroB olleH
3. String conversion function
Some functions for string conversion can be seen in the following table:
| Fungsi | File Header | Keterangan |
|----------|-------------|--------------------------------------------------------------------------|
| atof() | math.h | Digunakan untuk mengubah string (angka) menjadi blangan float |
| atoi() | stdlib.h | Digunakan untuk mengubah string (angka) menjadi blangan integer |
| atol() | stdlib.h | Digunakan untuk mengubah string (angka) menjadi blangan long integer |
| strlwr() | String.h | Digunakan untuk mengubah huruf kapital dalam string menjadi huruf kecil. |
| strupr() | strupr() | Digunakan untuk mengubah huruf kecil dalam string menjadi huruf kapital. |
Example program:
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
char teks[30];
char angka_s[10];
float angka_f;
int angka_i;
strcpy(teks, "Hello World");
strcpy(angka_s,"78.56");
angka_f = atof(angka_s) + 80;
angka_i = atoi(angka_s) + 12;
cout << "angka_f sekarang : " << angka_f;
cout << "\nangka_i sekarang : " << angka_i;
cout << "\nhuruf kecil : " << strlwr(teks);
cout << "\nhuruf kapital : " << strupr(teks);
getch();
}
Output:
current_f number: 158.56
current i_number: 90
lowercase letter: hello world
capital letter: HELLO WORLD
4. Exercise
Output:
String Array
Source Code:
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
#define jml 5
/**
*bundet.com
*/
void main()
{
char nama[jml][30];
//input
for (int i=0; i<jml; i++){
cout << "nama mahasiswa " <<(i+1) <<" : ";
gets(nama[i]);
}
//output
for (int x=0;x<jml;x++){
cout << nama[x];
}
getch();
}
Source:
STMIK El Rahma Yogyakarta Module. By Eding Muh. Saprudin, S.Kom
Question 1
HASTRI PINDHA Apr 9, 2016, 19:55:00 I want to ask, that's char teks[13]
, is the 13 character length or what? Because inputting sentences with more than 13 characters is still printed, thanks
ANONYMOUS May 16, 2016, 05:54:00 by using gets, for the second input string it always fails, even though the buffer has been cleared with fflush(stdin). are there any other alternative solutions? or why can't fflush be a solution?
FREESTYLER Aug 28, 2017, 10:17:00 Bro, I want to ask, I use it gets(nama[i])
so I can use spaces but it gets(nama[i])
doesn't work, instead it immediately executes the next command. Why is that?
Response 1
Hi Hastri Pindha, no, 13 is the length of the "string" where "string" is an encapsulation class of character array, while 'char' (character) is a primitive data type, so it can be concluded that the string consists of several characters, while the character stands alone. if the string is enclosed by double quotation marks ("_"), for example:
"a", "assalamualaikum", "halo" dll.
while the character is surrounded by single quotation marks ('_'), for example:
'a', 'hallo', 'assalamualaikum' dll.
Now, why in the example above teks[13]
the word 'assalamualaikum' which is 15 characters long (according to EYD) but actually only 1 character (programmatically) so that it can be displayed, because the length used is still at index 0, even though the total index is 12, why only up to 12? even though the length given is 13, because the string index starts from zero (0). So, if you want to use all lengths teks[13]
, then please change the code to be like this:
char teks[13]={'a','s','s','a','l','a','m','u','a','l','a','i','k','u','m'};
then an error notification will appear "Too many initializers"
Conclusion: So the difference lies here:
'a','s','s','a','l','a','m','u','a','l','a','i','k','u','m' tidak sama dengan 'assalamualaikum'
I think that's all Hastri Pindha, thanks for the discussion
clean it using clrscr(); bro, don't use that
Is the space meant as a time gap or a space for a character?, if for example a time gap just use break; or if you want to use a space for a regular character, create a variable specifically to hold the space, for example (space=" "
This discussion covers how to use strings in C++ programming including the basics of using strings and their supporting functions, while a further review is available here Strings in C++
1. String constants
String constants are written with double quotes ("_") at the beginning and at the end, for example: "Test"
The string constants above are stored in memory sequentially in the following order:
In the last character there is a NULL character (\0) which functions as the end of the string.
2. String variables
String variables are variables used to store string data, for example:
char nama[20];
3. Entering data from the keyboard
To enter data from the keyboard, cin is used, but the cin that we usually use cannot read spaces, so to overcome this we can use the getline() function, while sizeof is used to adjust the definition of array variables.
output:
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Konstanta String
*/
void main()
{
char nama[20];
char alamat[30];
cout<<"Masukan nama : ";
cin.getline(nama,sizeof(nama));
//sizeof, digunakan untuk menyesuaikan definisi arraynya
//jadi, kelebihannya adalah saat kita ingin menggunakannya di
//program selanjutnya, maka kita tidak perlu susah payah mengingat definisinya
//jadi tinggal mengingat variabelnya saja.
//dan seperti yang tadi sudah kita sampaikan bahwa getline digunakan untuk
//menampung spasi.
cout<<"Masukan alamat : ";
cin.getline(alamat,sizeof(alamat));
cout<<endl<<endl;
cout<<"Nama anda : "<<nama<<endl;
cout<<"Alamat anda : "<<alamat;
getch();
}
Hope this is useful & happy learning!
How to Copy a String in C++
Copying strings is different from copying numbers, in c++ to copy strings the strcpy() function is used. Why, because in arrays it does not use the = operation, for example: text 1 = text 2, this cannot be done because in the array duplication system it must be done one by one for each element, that is why strcpy() must be used.
output:
Example Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Menyalin String Dalam C++
*/
void main()
{
char teks1[50];
char teks2[50];
cout<<"Masukan teks 1 : ";
cin.getline(teks1,sizeof(teks1));
strcpy(teks2,teks1);
cout<<endl;
cout<<"Isi teks 2 : "<<teks2<<endl;
getch();
}
Hope this is useful & happy learning!
Understanding toupper() & tolower() in C++
Still about strings but this time about manipulation to upper and lower case. The toupper() function is to get a capital letter from a lower case letter, while tolower() is to get a lower case letter from a capital letter.
output:
Example Program:
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
/**
*bundet.com
*Manipulasi Font / Karakter
*/
void main()
{
char teks1[30];
char teks2[30];
cout<<"masukan huruf kecil : ";
cin.getline(teks1,sizeof(teks1));
for(int i=0;i<teks1[i];i++)
teks1[i]=toupper(teks1[i]);
cout<<endl;
cout<<"Isi teks 1 : "<<teks1<<endl<<endl;
cout<<"MASUKAN HURUF KAPITAL : ";
cin.getline(teks2,sizeof(teks2));
for(int i=0;i<teks2[i];i++)
teks2[i]=tolower(teks2[i]);
cout<<endl;
cout<<"isi teks 2 : "<<teks2<<endl;
getch();
}
Hope this is useful & happy learning!
strlen() Calculates String Length
Still about strings, but this review is simple, namely about calculating the length of the string that we will input, so that it makes it easier for us to know how many characters (including spaces), this function will be useful when we do coding for a form entry whose number of characters we need to limit.
output:
Example Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Menghitung Panjang String
*/
void main()
{
char teks[50];
cout<<"Ketik kalimat anda : ";
cin.getline(teks,sizeof(teks));
cout<<endl;
cout<<"Panjang string : ";
cout<<strlen(teks);
getch();
}
Hope this is useful & happy learning!
strcat() Concatenate Strings
Once again, it is still about strings and for this review, it is also still simple, namely about how to combine 2 or more strings that we will input, so that it allows us to display a number of strings in row format, we can use this when creating a form project.
output:
Example Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Menggabungkan 2 atau lebih String
*/
void main()
{
char teks1[50];
char teks2[50];
cout<<"Ketik nama depan anda : ";
cin.getline(teks1,sizeof(teks1));
cout<<endl;
cout<<"Ketik nama belakang anda : ";
cin.getline(teks2,sizeof(teks2));
cout<<endl;
cout<<"Nama lengkap anda adalah : ";
cout<<strcat(teks1,teks2);
getch();
}
Hope this is useful & happy learning!
Hidden String Password in C++
Anyone who is learning how to hide passwords with c++ programming, I'm sure they are students, and most of them use TurboC compiler. But if you are not a student and looking for this kind of code with the hope of being compatible with many platforms. Sorry, we don't have that capability yet.
Source Code:
#include<iostream.h>
#include<conio.h>
/*
Author:
Rammohan Alampally,
rammohan@india.com
Technical Lead,
Bangalore, India.
www.FindSyntax.com -> Worlds first Web based Windows O/S is a Brain Chaild of Rammohan
*/
void main()
{
clrscr();
cout<<"Enter password: \n";
restart:int x[100],x1[100],i,j=0,k=0,l;
for(i=0;i<=100;i++)
{
Rammohan:l=getch();
if(((l>=48)&&(l<=126))||(l==8)||(l==13))
x[i]=l;
else goto Rammohan;
if(x[i]==13)
break;
else if(x[i]==8)
{
gotoxy(1,2);
clreol();
for(i=0;i<100;i++)
x[i]='\0';
goto restart;
}
else
{
cout<<"*";
k++;
}
}
cout<<"\nRe enter password: \n";
for(i=0;i<=k;i++)
{
x1[i]=getche();
if(x1[i]==13)break;
}
for(i=0;i<=k;i++)
if(x[i]!=x1[i])
j++;
if(j==0)
cout<<"\nPasswords match!!\n";
else cout<<"\nPasswords do not match!!\n";
getch();
}
Output:
Hide String Like Password - C++