D Programming – Unions ”; Previous Next A union is a special data type available in D that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes. Defining a Union in D To define a union, you must use the union statement in very similar way as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows − union [union tag] { member definition; member definition; … member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union”s definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str − union Data { int i; float f; char str[20]; } data; A variable of Data type can store an integer, a floating-point number, or a string of characters. This means a single variable (same memory location) can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. The following example displays total memory size occupied by the above union − Live Demo import std.stdio; union Data { int i; float f; char str[20]; }; int main( ) { Data data; writeln( “Memory size occupied by data : “, data.sizeof); return 0; } When the above code is compiled and executed, it produces the following result − Memory size occupied by data : 20 Accessing Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Example The following example explains usage of union − Live Demo import std.stdio; union Data { int i; float f; char str[13]; }; void main( ) { Data data; data.i = 10; data.f = 220.5; data.str = “D Programming”.dup; writeln( “size of : “, data.sizeof); writeln( “data.i : “, data.i); writeln( “data.f : “, data.f); writeln( “data.str : “, data.str); } When the above code is compiled and executed, it produces the following result − size of : 16 data.i : 1917853764 data.f : 4.12236e+30 data.str : D Programming Here, you can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Now let us look into the same example once again where we will use one variable at a time which is the main purpose of having union − Modified Example Live Demo import std.stdio; union Data { int i; float f; char str[13]; }; void main( ) { Data data; writeln( “size of : “, data.sizeof); data.i = 10; writeln( “data.i : “, data.i); data.f = 220.5; writeln( “data.f : “, data.f); data.str = “D Programming”.dup; writeln( “data.str : “, data.str); } When the above code is compiled and executed, it produces the following result − size of : 16 data.i : 10 data.f : 220.5 data.str : D Programming Here, all the members are getting printed very well because one member is being used at a time. Print Page Previous Next Advertisements ”;
Category: d Programming
D Programming – Basic Syntax
D Programming – Basic Syntax ”; Previous Next D is quite simple to learn and lets start creating our first D program! First D Program Let us write a simple D program. All D files will have extension .d. So put the following source code in a test.d file. Live Demo import std.stdio; /* My first program in D */ void main(string[] args) { writeln(“test!”); } Assuming D environment is setup correctly, lets run the programming using − $ dmd test.d $ ./test We can see the following output. test Let us now see the basic structure of D program, so that it will be easy for you to understand basic building blocks of the D programming language. Import in D Libraries which are collections of reusable program parts can be made available to our project with the help of import. Here we import the standard io library which provides the basic I/O operations. writeln which is used in above program is a function in D”s standard library. It is used for printing a line of text. Library contents in D are grouped into modules which is based on the types of tasks that they intend perform. The only module that this program uses is std.stdio, which handles data input and output. Main Function Main function is the starting of the program and it determines the order of execution and how other sections of the program should be executed. Tokens in D A D program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following D statement consists of four tokens − writeln(“test!”); The individual tokens are − writeln ( “test!” ) ; Comments Comments are like supporting text in your D program and they are ignored by the compiler. Multi line comment starts with /* and terminates with the characters */ as shown below − /* My first program in D */ Single comment is written using // in the beginning of the comment. // my first program in D Identifiers A D identifier is a name used to identify a variable, function, or any other userdefined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). D does not allow punctuation characters such as @, $, and % within identifiers. D is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in D. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords The following list shows few of the reserved words in D. These reserved words may not be used as constant or variable or any other identifier names. abstract alias align asm assert auto body bool byte case cast catch char class const continue dchar debug default delegate deprecated do double else enum export extern false final finally float for foreach function goto if import in inout int interface invariant is long macro mixin module new null out override package pragma private protected public real ref return scope short static struct super switch synchronized template this throw true try typeid typeof ubyte uint ulong union unittest ushort version void wchar while with Whitespace in D A line containing only whitespace, possibly with a comment, is known as a blank line, and a D compiler totally ignores it. Whitespace is the term used in D to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − local age There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement int fruit = apples + oranges //get the total fruits No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose. Print Page Previous Next Advertisements ”;
D Programming – Environment
D Programming – Environment ”; Previous Next Local Environment Setup for D If you are still willing to set up your environment for D programming language, you need the following two softwares available on your computer, (a) Text Editor,(b)D Compiler. Text Editor for D Programming This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for D programs are named with the extension “.d“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, build it and finally execute it. The D Compiler Most current D implementations compile directly into machine code for efficient execution. We have multiple D compilers available and it includes the following. DMD − The Digital Mars D compiler is the official D compiler by Walter Bright. GDC − A front-end for the GCC back-end, built using the open DMD compiler source code. LDC − A compiler based on the DMD front-end that uses LLVM as its compiler back-end. The above different compilers can be downloaded from D downloads We will be using D version 2 and we recommend not to download D1. Lets have a helloWorld.d program as follows. We will use this as first program we run on platform you choose. Live Demo import std.stdio; void main(string[] args) { writeln(“Hello World!”); } We can see the following output. $ hello world Installation of D on Windows Download the windows installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − C:DProgramming> DMD helloWorld.d C:DProgramming> helloWorld We can see the following output. hello world C:DProgramming is the folder, I am using to save my samples. You can change it to the folder that you have saved D programs. Installation of D on Ubuntu/Debian Download the debian installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on Mac OS X Download the Mac installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on Fedora Download the fedora installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world Installation of D on OpenSUSE Download the OpenSUSE installer. Run the downloaded executable to install the D which can be done by following the on screen instructions. Now we can build and run a d file say helloWorld.d by switching to folder containing the file using cd and then using the following steps − $ dmd helloWorld.d $ ./helloWorld We can see the following output. $ hello world D IDE We have IDE support for D in the form of plugins in most cases. This includes, Visual D plugin is a plugin for Visual Studio 2005-13 DDT is a eclipse plugin that provides code completion, debugging with GDB. Mono-D code completion, refactoring with dmd/ldc/gdc support. It has been part of GSoC 2012. Code Blocks is a multi-platform IDE that supports D project creation, highlighting and debugging. Print Page Previous Next Advertisements ”;
D Programming – Overview
D Programming – Overview ”; Previous Next D programming language is an object-oriented multi-paradigm system programming language developed by Walter Bright of Digital Mars. Its development started in 1999 and was first released in 2001. The major version of D(1.0) was released in 2007. Currently, we have D2 version of D. D is language with syntax being C style and uses static typing. There are many features of C and C++ in D but also there are some features from these language not included part of D. Some of the notable additions to D includes, Unit testing True modules Garbage collection First class arrays Free and open Associative arrays Dynamic arrays Inner classes Closures Anonymous functions Lazy evaluation Closures Multiple Paradigms D is a multiple paradigm programming language. The multiple paradigms includes, Imperative Object Oriented Meta programming Functional Concurrent Example Live Demo import std.stdio; void main(string[] args) { writeln(“Hello World!”); } Learning D The most important thing to do when learning D is to focus on concepts and not get lost in language technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. Scope of D D programming has some interesting features and the official D programming site claims that D is convinient, powerful and efficient. D programming adds many features in the core language which C language has provided in the form of Standard libraries such as resizable array and string function. D makes an excellent second language for intermediate to advanced programmers. D is better in handling memory and managing the pointers that often causes trouble in C++. D programming is intended mainly on new programs that conversion of existing programs. It provides built in testing and verification an ideal for large new project that will be written with millions of lines of code by large teams. Print Page Previous Next Advertisements ”;
D Programming – Home
D Programming Tutorial PDF Version Quick Guide Resources Job Search Discussion D programming language is an object-oriented multi-paradigm system programming language. D programming is actually developed by re-engineering C++ programming language, but it is distinct programming language that not only takes in some features of C++ but also some features of other programming languages such as Java, C#, Python, and Ruby. This tutorial covers various topics ranging from the basics of the D programming language to advanced OOP concepts along with the supplementary examples. Audience This tutorial is designed for all those individuals who are looking for a starting point of learning D Language. Both a beginner or advanced users can refer this tutorial as their learning material. Enthusiastic learners can refer it as their on-the-go reading reference. Ayn individual with logical mindset can enjoy learning D through this tutorial. Prerequisites Before proceeding with this tutorial, it is advisable for you to understand the basics concepts of computer programming. You just need to have a basic understanding of working with a simple text editor and command line. Print Page Previous Next Advertisements ”;
D Programming – Tuples
D Programming – Tuples ”; Previous Next Tuples are used for combining multiple values as a single object. Tuples contains a sequence of elements. The elements can be types, expressions, or aliases. The number and elements of a tuple are fixed at compile time and they cannot be changed at run time. Tuples have characteristics of both structs and arrays. The tuple elements can be of different types like structs. The elements can be accessed via indexing like arrays. They are implemented as a library feature by the Tuple template from the std.typecons module. Tuple makes use of TypeTuple from the std.typetuple module for some of its operations. Tuple Using tuple() Tuples can be constructed by the function tuple(). The members of a tuple are accessed by index values. An example is shown below. Example Live Demo import std.stdio; import std.typecons; void main() { auto myTuple = tuple(1, “Tuts”); writeln(myTuple); writeln(myTuple[0]); writeln(myTuple[1]); } When the above code is compiled and executed, it produces the following result − Tuple!(int, string)(1, “Tuts”) 1 Tuts Tuple using Tuple Template Tuple can also be constructed directly by the Tuple template instead of the tuple() function. The type and the name of each member are specified as two consecutive template parameters. It is possible to access the members by properties when created using templates. Live Demo import std.stdio; import std.typecons; void main() { auto myTuple = Tuple!(int, “id”,string, “value”)(1, “Tuts”); writeln(myTuple); writeln(“by index 0 : “, myTuple[0]); writeln(“by .id : “, myTuple.id); writeln(“by index 1 : “, myTuple[1]); writeln(“by .value “, myTuple.value); } When the above code is compiled and executed, it produces the following result Tuple!(int, “id”, string, “value”)(1, “Tuts”) by index 0 : 1 by .id : 1 by index 1 : Tuts by .value Tuts Expanding Property and Function Params The members of Tuple can be expanded either by the .expand property or by slicing. This expanded/sliced value can be passed as function argument list. An example is shown below. Example Live Demo import std.stdio; import std.typecons; void method1(int a, string b, float c, char d) { writeln(“method 1 “,a,”t”,b,”t”,c,”t”,d); } void method2(int a, float b, char c) { writeln(“method 2 “,a,”t”,b,”t”,c); } void main() { auto myTuple = tuple(5, “my string”, 3.3, ”r”); writeln(“method1 call 1”); method1(myTuple[]); writeln(“method1 call 2”); method1(myTuple.expand); writeln(“method2 call 1”); method2(myTuple[0], myTuple[$-2..$]); } When the above code is compiled and executed, it produces the following result − method1 call 1 method 1 5 my string 3.3 r method1 call 2 method 1 5 my string 3.3 r method2 call 1 method 2 5 3.3 r TypeTuple TypeTuple is defined in the std.typetuple module. A comma-separated list of values and types. A simple example using TypeTuple is given below. TypeTuple is used to create argument list, template list, and array literal list. Live Demo import std.stdio; import std.typecons; import std.typetuple; alias TypeTuple!(int, long) TL; void method1(int a, string b, float c, char d) { writeln(“method 1 “,a,”t”,b,”t”,c,”t”,d); } void method2(TL tl) { writeln(tl[0],”t”, tl[1] ); } void main() { auto arguments = TypeTuple!(5, “my string”, 3.3,”r”); method1(arguments); method2(5, 6L); } When the above code is compiled and executed, it produces the following result − method 1 5 my string 3.3 r 5 6 Print Page Previous Next Advertisements ”;
D Programming – Associative Arrays ”; Previous Next Associative arrays have an index that is not necessarily an integer, and can be sparsely populated. The index for an associative array is called the Key, and its type is called the KeyType. Associative arrays are declared by placing the KeyType within the [ ] of an array declaration. A simple example for associative array is shown below. Live Demo import std.stdio; void main () { int[string] e; // associative array b of ints that are e[“test”] = 3; writeln(e[“test”]); string[string] f; f[“test”] = “Tuts”; writeln(f[“test”]); writeln(f); f.remove(“test”); writeln(f); } When the above code is compiled and executed, it produces the following result − 3 Tuts [“test”:”Tuts”] [] Initializing Associative Array A simple initialization of associative array is shown below. Live Demo import std.stdio; void main () { int[string] days = [ “Monday” : 0, “Tuesday” : 1, “Wednesday” : 2, “Thursday” : 3, “Friday” : 4, “Saturday” : 5, “Sunday” : 6 ]; writeln(days[“Tuesday”]); } When the above code is compiled and executed, it produces the following result − 1 Properties of Associative Array Here are the properties of an associative array − Sr.No. Property & Description 1 .sizeof Returns the size of the reference to the associative array; it is 4 in 32-bit builds and 8 on 64-bit builds. 2 .length Returns number of values in the associative array. Unlike for dynamic arrays, it is read-only. 3 .dup Create a new associative array of the same size and copy the contents of the associative array into it. 4 .keys Returns dynamic array, the elements of which are the keys in the associative array. 5 .values Returns dynamic array, the elements of which are the values in the associative array. 6 .rehash Reorganizes the associative array in place so that lookups are more efficient. rehash is effective when, for example, the program is done loading up a symbol table and now needs fast lookups in it. Returns a reference to the reorganized array. 7 .byKey() Returns a delegate suitable for use as an Aggregate to a ForeachStatement which will iterate over the keys of the associative array. 8 .byValue() Returns a delegate suitable for use as an Aggregate to a ForeachStatement which will iterate over the values of the associative array. 9 .get(Key key, lazy Value defVal) Looks up key; if it exists returns corresponding value else evaluates and returns defVal. 10 .remove(Key key) Removes an object for key. Example An example for using the above properties is shown below. Live Demo import std.stdio; void main () { int[string] array1; array1[“test”] = 3; array1[“test2”] = 20; writeln(“sizeof: “,array1.sizeof); writeln(“length: “,array1.length); writeln(“dup: “,array1.dup); array1.rehash; writeln(“rehashed: “,array1); writeln(“keys: “,array1.keys); writeln(“values: “,array1.values); foreach (key; array1.byKey) { writeln(“by key: “,key); } foreach (value; array1.byValue) { writeln(“by value “,value); } writeln(“get value for key test: “,array1.get(“test”,10)); writeln(“get value for key test3: “,array1.get(“test3”,10)); array1.remove(“test”); writeln(array1); } When the above code is compiled and executed, it produces the following result − sizeof: 8 length: 2 dup: [“test”:3, “test2”:20] rehashed: [“test”:3, “test2”:20] keys: [“test”, “test2”] values: [3, 20] by key: test by key: test2 by value 3 by value 20 get value for key test: 3 get value for key test3: 10 [“test2″:20] Print Page Previous Next Advertisements ”;
D Programming – Pointers
D Programming – Pointers ”; Previous Next D programming pointers are easy and fun to learn. Some D programming tasks are performed more easily with pointers, and other D programming tasks, such as dynamic memory allocation, cannot be performed without them. A simple pointer is shown below. Instead of directly pointing to the variable, pointer points to the address of the variable. As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which prints the address of the variables defined − Live Demo import std.stdio; void main () { int var1; writeln(“Address of var1 variable: “,&var1); char var2[10]; writeln(“Address of var2 variable: “,&var2); } When the above code is compiled and executed, it produces the following result − Address of var1 variable: 7FFF52691928 Address of var2 variable: 7FFF52691930 What Are Pointers? A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer”s base type; it must be a valid programming type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However; in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration − int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. Using Pointers in D programming There are few important operations, when we use the pointers very frequently. we define a pointer variables assign the address of a variable to a pointer finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations − Live Demo import std.stdio; void main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable writeln(“Value of var variable: “,var); writeln(“Address stored in ip variable: “,ip); writeln(“Value of *ip variable: “,*ip); } When the above code is compiled and executed, it produces the following result − Value of var variable: 20 Address stored in ip variable: 7FFF5FB7E930 Value of *ip variable: 20 Null Pointers It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned null is called a null pointer. The null pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program − Live Demo import std.stdio; void main () { int *ptr = null; writeln(“The value of ptr is ” , ptr) ; } When the above code is compiled and executed, it produces the following result − The value of ptr is null On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However; the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. By convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer you can use an if statement as follows − if(ptr) // succeeds if p is not null if(!ptr) // succeeds if p is null Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables hold some junk values and it becomes difficult to debug the program. Pointer Arithmetic There are four arithmetic operators that can be used on pointers: ++, –, +, and – To understand pointer arithmetic, let us consider an integer pointer named ptr, which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmatic operation on the pointer − ptr++ then the ptr will point to the location 1004 because each time ptr is incremented, it points to the next integer. This operation will move the pointer to next memory location without impacting the actual value at the memory location. If ptr points to a character whose address is 1000, then the above operation points to the location 1001 because next character will be available at 1001. Incrementing a Pointer We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array − Live Demo import std.stdio; const int MAX = 3; void main () { int var[MAX] = [10, 100, 200]; int *ptr = &var[0]; for (int i = 0; i < MAX; i++, ptr++) { writeln(“Address of var[” , i , “] = “,ptr); writeln(“Value of var[” , i , “] = “,*ptr); } } When the above code is compiled and executed, it produces the following result − Address of var[0] = 18FDBC Value of var[0] = 10 Address of var[1] =
D Programming – Strings
D Programming – Strings ”; Previous Next D provides following two types of string representations − Character array Core language string Character Array We can represent the character array in one of the two forms as shown below. The first form provides the size directly and the second form uses the dup method which creates a writable copy of the string “Good morning”. char[9] greeting1 = “Hello all”; char[] greeting2 = “Good morning”.dup; Example Here is a simple example using the above simple character array forms. Live Demo import std.stdio; void main(string[] args) { char[9] greeting1 = “Hello all”; writefln(“%s”,greeting1); char[] greeting2 = “Good morning”.dup; writefln(“%s”,greeting2); } When the above code is compiled and executed, it produces result something as follows − Hello all Good morning Core Language String Strings are built-in to the core language of D. These strings are interoperable with the character array shown above. The following example shows a simple string representation. string greeting1 = “Hello all”; Example Live Demo import std.stdio; void main(string[] args) { string greeting1 = “Hello all”; writefln(“%s”,greeting1); char[] greeting2 = “Good morning”.dup; writefln(“%s”,greeting2); string greeting3 = greeting1; writefln(“%s”,greeting3); } When the above code is compiled and executed, it produces result something as follows − Hello all Good morning Hello all String Concatenation String concatenation in D programming uses the tilde(~) symbol. Example Live Demo import std.stdio; void main(string[] args) { string greeting1 = “Good”; char[] greeting2 = “morning”.dup; char[] greeting3 = greeting1~” “~greeting2; writefln(“%s”,greeting3); string greeting4 = “morning”; string greeting5 = greeting1~” “~greeting4; writefln(“%s”,greeting5); } When the above code is compiled and executed, it produces result something as follows − Good morning Good morning Length of String The length of string in bytes can retrieved with the help of the length fuction. Example Live Demo import std.stdio; void main(string[] args) { string greeting1 = “Good”; writefln(“Length of string greeting1 is %d”,greeting1.length); char[] greeting2 = “morning”.dup; writefln(“Length of string greeting2 is %d”,greeting2.length); } When the above code is compiled and executed, it produces the following result − Length of string greeting1 is 4 Length of string greeting2 is 7 String Comparison String comparison is quite easy in D programming. You can use the ==, <, and > operators for string comparisons. Example Live Demo import std.stdio; void main() { string s1 = “Hello”; string s2 = “World”; string s3 = “World”; if (s2 == s3) { writeln(“s2: “,s2,” and S3: “,s3, ” are the same!”); } if (s1 < s2) { writeln(“””, s1, “” comes before ””, s2, “”.”); } else { writeln(“””, s2, “” comes before ””, s1, “”.”); } } When the above code is compiled and executed, it produces result something as follows − s2: World and S3: World are the same! ”Hello” comes before ”World”. Replacing Strings We can replace strings using the string[]. Example Live Demo import std.stdio; import std.string; void main() { char[] s1 = “hello world “.dup; char[] s2 = “sample”.dup; s1[6..12] = s2[0..6]; writeln(s1); } When the above code is compiled and executed, it produces result something as follows − hello sample Index Methods Index methods for location of a substring in string including indexOf and lastIndexOf are explained in the following example. Example Live Demo import std.stdio; import std.string; void main() { char[] s1 = “hello World “.dup; writeln(“indexOf of llo in hello is “,std.string.indexOf(s1,”llo”)); writeln(s1); writeln(“lastIndexOf of O in hello is ” ,std.string.lastIndexOf(s1,”O”,CaseSensitive.no)); } When the above code is compiled and executed, it produces the following result − indexOf.of llo in hello is 2 hello World lastIndexOf of O in hello is 7 Handling Cases Methods used for changing cases is shown in the following example. Example Live Demo import std.stdio; import std.string; void main() { char[] s1 = “hello World “.dup; writeln(“Capitalized string of s1 is “,capitalize(s1)); writeln(“Uppercase string of s1 is “,toUpper(s1)); writeln(“Lowercase string of s1 is “,toLower(s1)); } When the above code is compiled and executed, it produces the following result − Capitalized string of s1 is Hello world Uppercase string of s1 is HELLO WORLD Lowercase string of s1 is hello world Restricting Characters Restring characters in strings are shown in the following example. Example Live Demo import std.stdio; import std.string; void main() { string s = “H123Hello1”; string result = munch(s, “0123456789H”); writeln(“Restrict trailing characters:”,result); result = squeeze(s, “0123456789H”); writeln(“Restrict leading characters:”,result); s = ” Hello World “; writeln(“Stripping leading and trailing whitespace:”,strip(s)); } When the above code is compiled and executed, it produces the following result − Restrict trailing characters:H123H Restrict leading characters:ello1 Stripping leading and trailing whitespace:Hello World Print Page Previous Next Advertisements ”;
D Programming – Characters
D Programming – Characters ”; Previous Next Characters are the building blocks of strings. Any symbol of a writing system is called a character: letters of alphabets, numerals, punctuation marks, the space character, etc. Confusingly, the building blocks of characters themselves are called characters as well. The integer value of the lowercase a is 97 and the integer value of the numeral 1 is 49. These values have been assigned merely by conventions when the ASCII table has been designed. The following table mentions standard character types with their storage sizes and purposes. The characters are represented by the char type, which can hold only 256 distinct values. If you are familiar with the char type from other languages, you may already know that it is not large enough to support the symbols of many writing systems. Type Storage size Purpose char 1 byte UTF-8 code unit wchar 2 bytes UTF-16 code unit dchar 4 bytes UTF-32 code unit and Unicode code point Some useful character functions are listed below − isLower − Determines if a lowercase character? isUpper − Determines if an uppercase character? isAlpha − Determines if a Unicode alphanumeric character (generally, a letter or a numeral)? isWhite − Determines if a whitespace character? toLower − It produces the lowercase of the given character. toUpper − It produces the uppercase of the given character. Live Demo import std.stdio; import std.uni; void main() { writeln(“Is ğ lowercase? “, isLower(”ğ”)); writeln(“Is Ş lowercase? “, isLower(”Ş”)); writeln(“Is İ uppercase? “, isUpper(”İ”)); writeln(“Is ç uppercase? “, isUpper(”ç”)); writeln(“Is z alphanumeric? “, isAlpha(”z”)); writeln(“Is new-line whitespace? “, isWhite(”n”)); writeln(“Is underline whitespace? “, isWhite(”_”)); writeln(“The lowercase of Ğ: “, toLower(”Ğ”)); writeln(“The lowercase of İ: “, toLower(”İ”)); writeln(“The uppercase of ş: “, toUpper(”ş”)); writeln(“The uppercase of ı: “, toUpper(”ı”)); } When the above code is compiled and executed, it produces the following result − Is ğ lowercase? true Is Ş lowercase? false Is İ uppercase? true Is ç uppercase? false Is z alphanumeric? true Is new-line whitespace? true Is underline whitespace? false The lowercase of Ğ: ğ The lowercase of İ: i The uppercase of ş: Ş The uppercase of ı: I Reading Characters in D We can read characters using readf as shown below. readf(” %s”, &letter); Since D programming support unicode, in order to read unicode characters, we need to read twice and write twice to get the expected result. This does not work on the online compiler. The example is shown below. import std.stdio; void main() { char firstCode; char secondCode; write(“Please enter a letter: “); readf(” %s”, &firstCode); readf(” %s”, &secondCode); writeln(“The letter that has been read: “, firstCode, secondCode); } When the above code is compiled and executed, it produces the following result − Please enter a letter: ğ The letter that has been read: ğ Print Page Previous Next Advertisements ”;