Anda di halaman 1dari 23

Kuliah 3

STRUKTUR DATA
Type Data String

Type Data Terstruktur


String Reference

Type Data Terstruktur


C String Declaration

Deklarasi :
C string biasanya di deklasi sebagai array of char, namun perlu
diperhatikan bahwa array of char tidaklah otomatis sebuah
string.
Valid C string harus di ahiri oleh karakter null, yaitu sebuah
karakter ascii bernilai 0 (nol) atau sering ditulis sebagai \0
Char adalah type data built in pada c, sehingga membuat array
of char tdk diperlukan header file, namun untuk memprosesnya
kita membutuhkan fungsi dan utilty, maka untuk
mengoperasikannya kita perlu meng-include header file
<include cstring.h>
Contoh deklarasi sebagai array of char :
char S1[20];
ini adalah deklarasi array of char yang dapat menyimpan string

Type Data Terstruktur


C String Declaration

Cara deklarasi array of char untuk membentuk string c yang


valid adalah sbb :
char S1[20]={ h , e , l , l , o, \0 };
harus di ahiri null

// string

char S1[20]=hello;
singkat

// deklarasi

char S1[20]=
kosong

// string

Kita juga dapat mendeklarasi c string sebagai pointer of char


sbb :
char* S3 = hello jadi array sebetulnya adalah pointer
Hal di atas akan membuat character array sejumlah string itu
dengan terminasi nul nya, dan menempatkan addres elemen

Type Data Terstruktur


Representasi C string di dalam memory

char name[10]=karen, dgn adanya tanda petik maka


kompiler akan otomatis menganggap array of char diatas
adalah string dan akan menambahkan \0 di ahir, elemen
setelah null bukan bagian dari string

Null string adalah string dengan karakter null sebagai


awalan, panjang dari null string adalah 0

C String bisa Input and Output dengan operator C++


operator >> dapat digunakan untuk membaca menjadi character
array seperti C string. operator << may be used menampilkan isi
array sebagaimana C string / string literal.

C Input String
//--------------------------------------------------------------------------#include <stdio.h>
#include <iostream.h>
#include <conio.h>
// utk getch()
#include <clx.h>
#pragma hdrstop
//--------------------------------------------------------------------------#pragma argsused
int main(int argc, char* argv[])
{
char str[20];
printf("Enter your string : ");
scanf("%[^\t\n]s",str);
// scanf to accept multiword string
printf("String = %s",str);
string
getch();

// display the entered


// wait for key

return 0;}
//---------------------------------------------------------------------------

C++ Input String

//--------------------------------------------------------------------#include <stdio.h>
#include <iostream.h>
#include <conio.h>
// utk
getch()

//-------------------------------------------------------------------------#include <stdio.h>
#include <iostream.h>
#include <conio.h>
// utk getch()

#include <clx.h>
#pragma hdrstop
#include <clx.h>
//-------------------------------------------------------------------------#pragma hdrstop
#pragma argsused
//-------------------------------------------------- int main(int argc, char* argv[])
-------------------{
#pragma argsused
char nama[40];
int main(int argc, char* argv[])
{
cout << "nama : ";
char nama[40];
cin >> nama;
printf("nama : ");
cin.getline(nama,40);

cout << "nama : " << nama;


getch();

printf("nama : %s",nama);
getch();

return 0;

return 0;
}
//--------------------------------------------------

}
//--------------------------------------------------------------------------

Type Data Terstruktur


C Subscript, Length
The string subscript :
char* s3 = "hello";
cout << s3[1] << endl;
string "Hello

// Prints the character 'e', the second character in the

Karena S3 adalah pointer maka kita juga dapat mengakses individual charakter
dari stringnya via pointernya, contoh :
cout << *s3 << endl;
// Prints the character 'h', the character pointed to by
s3
cout << *(s3 + 4) << endl; // Prints the character 'o', the fifth character in the
string "Hello
String Length :
You can obtain the length of a C string using the C library function strlen().
This function takes a character pointer that points to a C string as an argument.
It returns an unsigned int, the number of valid characters in the string (not
including the null char).

Latihan 1 : Buat Program


Assign s secara langsung
Examples :
Screen Capture length &
char s[20] = "Some text";
cout << "String length is " << strlen(s) << endl; // Length
is 9 Array-nya
Elemen

Type Data Terstruktur


Subscript, Length, Compare
Comparing C strings using the relational operators ==, !=, >, <, >=, and <= does
not work correctly,
since the array names will be converted to pointers.
For example, the expression :
if (s1 == s2)
actually compares the addresses of the first elements of the arrays s1 and s2, not
their contents.
Since those addresses are different, the relational expression is always false.
To compare the contents of two C strings, you should use the C library function
strcmp().
if (strcmp(s1,
if (strcmp(s1,
if (strcmp(s1,
if (strcmp(s1,
if (strcmp(s1,
if (strcmp(s1,
s2

s2)
s2)
s2)
s2)
s2)
s2)

< 0) // If the C string s1 is less than the C string s2


== 0) // If the C string s1 is equal to the C string s2
> 0) // If the C string s1 is greater than the C string s2
<= 0) // If the C string s1 is less than or equal to the C string s2
!= 0) // If the C string s1 is not equal to the C string s2
>= 0) // If the C string s1 is greater
than or2equal
to Program
the C string
Latihan
: Buat

Baca S1 & S2 bandingkan..


Screen Capture hasilnya

Type Data Terstruktur


Subscript, Length, Compare, Concat
Concatenation :
The C library function strcat() can be used to concatenate C strings.
This function takes two arguments:
1) a pointer to a destination character array that contains a valid C string,
2) a pointer to a valid C string or string literal.
The function returns a pointer to the destination array, although this return value is
frequently ignored.
char s1[20] = "Hello";
char s2[20] = "friend";
strcat(s1, ", my "); // s1 now contains "Hello, my "
strcat(s1, s2); // s1 now contains "Hello, my friend"
The destination array must be large enough to hold the combined strings (including
the null character). If it is not, the array will overflow.

Latihan 3 : Buat Program


Assign S1 & S2 gabungkan..
Screen Capture hasilnya

Type Data Terstruktur


C String Assignment
char s1[20] = "This is a string";
s1 = "Another string";

// error: invalid array assignment

Hal diatas adalah salah, operator = menyebabkan kompiler c


menginterpretasinya sebagai ubah address pada variable array, bukan
mengubah isinya.
char s2[20];
s2 = s1;
berisi S1

// Hal ini benar, akan menyebabkan S2

Untuk mengubah isi string harus menggunakan fungsi sbb :


char s1[20];
char s2[20] = "Another new string";
strcpy(s1, "");
// Contents of s1 changed to null string
strcpy(s1, "new string");
// Contents of s1 changed to "new string"
strcpy(s1, s2);
// Contents of s1 changed to "Another
new string

Latihan 4 : Buat Program

Harus berhati-hati dengan assignment, bila panjang string yg menerima lebih


Assign S1 & S2 coba copy string tsb
pendek akan mengakibatkan run time error

Screen Capture hasilnya

Type Data Terstruktur


C++ string
Deklarasi :
C++ string adalah object dari class string, yang didefinisikan pada
header file <string> dan juga yang terkandung pada standard
namespace.
string class mempunyai beberapa konstruktor yang bisa dipakai
untuk membuat objeknya baik secara eksplisit atau implisiticitly)
Contoh :
string s1; // Default constructor, membuat string kosong,
panjang=0, atau sama dg ""
string s2("hello"); // Explicit constructor call to initialize new object
with C string
string s3 = "hello"; // Implicit constructor call to initialize new object
with C string
string s4(s2);
// Explicit constructor call to initialize new object
with C++ string
string s5 = s2;
// Implicit constructor call to initialize new object
with C++ string

Type Data Terstruktur


Representasi C++ string dalam memory
string name = "Karen";
//Here is another example of declaring a
C++ string:
name adalah object string dengan beberapa Field data. Field p
adalah pointer yang berisi addres (awal karakter). Field length berisi
panjang string, dan field capacity berisi jumlah characters yang
dapat ditampungnya beserta null stringnya

Panjang dari null string adalah 0.

Type Data Terstruktur


C++ string Subscript,Length
The subscript operator may be used to access the individual characters of a C++ string:
string s3 = "hello";
cout << s3[1] << endl;

// Prints the character 'e', the second character in the string "Hello"

The reason this works is a C++ feature called operator overloading. Its actually calls a special
member function named operator[] that has been defined as part of the string class.
The subscript specified inside the brackets is passed as an argument to the member function,
which then returns the character at that position in the string.
The name of a C++ string object is not a pointer and you can not use pointer notation with it
or perform pointer arithmetic on it.
String Length :
You can obtain the length of a C++ string using the string class methods length() or size().
Both of methods return an unsigned int.
the number of valid characters in the string (not including the null character).
Examples :
string s = "Some text";
cout << "String length is " << s.length() << endl; // Length is 9
// Loop through characters of string
for (int i = 0; i < (int) s.size(); i++)
cout << s[i];
cout << endl;

Type Data Terstruktur


C++ string Compare, Concat, Paassing & Returning
String Comparison :
C++ strings may be compared using the relational operators ==, !=, >, <, >=, and <=.
C++ string may be compared to either another C++ string or a valid C string, including a
string literal.
All such relational expressions resolve to the Boolean
values
true orProgram
false.
Latihan
6 : Buat
dgn String

C++
S1 & S2 coba bandingkan dgn operator ts
Screen Capture hasilnya

Examples :
if (s1 > s2) // Compare two C++ strings
if ("cat" == s2) // Compare C string literal and C++ string
if (s3 != cstr) // Compare C++ string and array containing C string
Like subscripting, this works because of operator overloading.

Concatenation :
The operator + may be used to concatenate C++ strings.
C++ strings, C strings, and string literals may all be concatenated together in any order.
The result is a C++ string object that may be assigned to another C++ string object, passed
Latihan
7 : Buat printed,
Program
to a function that takes a C++ string object
as an argument,
etc.
string s1 = "Hello";
string s2 = " good ";
char s3[10] = "friend";
s1 = s1 + ", my " + s2 + s3;

String C++ S1,S2,S3 coba gabung string tsb..


Screen Capture hasilnya

// s1 now contains "Hello, my good friend"

Passing and returning :


C++ string objects are passed and returned by value by default. This results in a copy of the
string object being created.
To save memory (and a possible call to the copy constructor), a string object is frequently
passed by reference instead. ini salah satu gunanya pointer

Type Data Terstruktur


C++ string assignment dan I/O
Beberpa cara assign C++ string/C string,/C string seperti C++ string.
Contoh :
string s1 = "original string"; Latihan 8 : Buat Program
string s2 = "new string";
String C++ S1,S2,S3 coba Assignment tsb..
char s3[20] = "another string";
Screen Capture hasilnya
s1 = s2; // s1 changed to "new string"
s1 = s3; // s1 changed to "another string"
s1 = "yet another string"; // s1 changed to "yet another string"
Once again, this works because of operator overloading.
Input and Output
operator >> digunakan untuk membaca data dan menjadikannya C+
+ string object.
operator << digunakan untuk menampilkan C++ string object.

Type Data Terstruktur


Konversi antar type string
Fungsi2 string
C

C string / string literal/ array of char :


char S1[20]={ h , e , l , l , o, \0 };
char S1[20]=hello;
char* S3 = hello
Konversi
C++ string :
string s1;
string s2("hello");
string s3 = "hello";

Fungsi2 string
C++

Type Data Terstruktur


Konversi antar type string
Seringkali kita mempunyai suatu type string tapi ingin menggunakan
fungsi pada type string lainnya, maka kita butuh cara konversinya.
Kita dapat membuat objek string C++ string dari C string / string
literal/ array of char. Buatlah string object kemudian pass C string /
string literal sbg constructor argument menggunakan method c_str()
Latihan 9 : Buat Program String C & C++
coba Assignment dgn fungsi strcpy tsb..
char s1[20];
Screen Capture hasilnya
string s2 = "My C++ string";
strcpy(s1, s2.c_str());

// c_str memberikan pointer dari string s2

Note : C string yang dibuat dgn cara ini tidak bisa diubah tapi bisa
digunakan untuk ditampilkan atau di copy.

Type Data Terstruktur


Pilih type string mana ??
Tentu gunakan sedapat mungkin type string C++ (since arrays are
evil).
Namun kadang kita tidak dapat menghindari C strings.
Misal menghadapi hal sbb :
Command line arguments passingnya ke main() menggunakan C
strings
File names harus dispesifikasi dengan C strings untuk
membukanya
Sejumlah fungsi library C string tidak ada ekivalensinya pada
string C++ string
String C++ tidak bisa distreaming ke serialized in binary format
(file) tanpa membuat kode (program) ekstra lebih mudah
menggunakan type string C
In Short, a good C++ programmer needs to understand and be able
to manipulate both types of strings.

Type Data Terstruktur


Pilih type string mana ??

Type Data Terstruktur


Resume String C and C++ Style

Type Data Terstruktur


String C and C++ Style

Type Data Terstruktur


String Function

Anda mungkin juga menyukai