Tag Archives: string

Combining types in output statements in C#

This tutorial shows you how you can combine types in a Console.WriteLine() output statement. For example, you can combine a string with an integer or float value. Watch the video below and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(message + result); // String and float value combined in output statement
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Converting variable types in C#

Data types in Java

A data type classifies various types of data eg. String, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the most commonly used data types used in the Java programming language.

Type Description Example
int The integer (int) data type stores positive or negative whole number values. 20
float The float data type stores floating point numbers (numbers with decimal places) eg. 43.65 . Often, you will need to end a float value with an ‘f’ character eg. 43.65f 43.65f
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is always surrounded by single quotes eg. ‘a’. ‘a’
String The String data type stores letters, numbers and other characters in the form of words or sentences. A string value is always surrounded by double quotes eg. “Hello World”. “Hello world”
boolean The boolean data type stores true or false values only eg. true true

The table below shows some of the other data types used in the Java programming language.

Type Description Example
byte The byte data type stores integer numbers ranging from -128 to +127 118
short The short data type is used for integer numbers ranging from -32,768 to +32,767 -28,471
long The long data type is used for integer values exceeding 2.14 billion ‘a’
double The double data type is used for extremely long floating point numbers 1.7976931348623157 × 10^308

Sample code

The sample Java code below shows how some of the different data types can be stored in variables. Later on, we will look at how to actually work with the values of different data types (eg. math calculations with integers and floats, and decision making with booleans).

The code includes comments explaining each data type.

package myjavaproject;

public class DataTypes {
    public static void main (String[] args){
        String message = "Hello"; // variable of String data type
        char letter = 'a'; // variable of char data type
        int number = 20; // variabe of int (integer) data type
        float decimal = 43.65f; // variable of float (floating point) data type
        boolean result = true; // variable of Boolean data type
        
        // now let's output the values of the different variables
        System.out.println("Message is " + message);
        System.out.println("Letter is " + letter);
        System.out.println("Age is " + number);
        System.out.println("Score is " + decimal);
        System.out.println("The answer is " + result);
    }
}

Variables in Java

In this tutorial you will learn how to create variables in the Java programming language. Variables are used to store data in a program.  A variable is like a ‘container’ that can store a value that can be used within the program. These values can be accessed, used and modified throughout the code.

Examples of values that you might need to store in a program include the score in a game, the user’s name, a password, or numbers used in calculations. Variables can store values of different data types – we’ll look at these in the next tutorial.

Variables have three important properties:

  • Variable name (identifier) – the actual name of the variable eg. score, username, age, price. Each variable must have a unique name. Some variable names can’t be used if they are the same as a reserved word used elsewhere in the language for other things such as a function. Variable names often cannot contain spaces or start with digits (rules vary in different languages)
  • Data type – the type of data that the variable will be storing such as text or numbers. There are special names for different data types that we will look at in the next tutorial
  • Value – the actual information being stored in the variable such a “Bob” for a variable called firstName or 26 for a variable called age.

The example below shows a new variable called message being created in the Java language. The variable is of the String data type (text that can contain letters, numbers and different characters) and is given an initial value of “Hello“.

java_variables

When you create a variable in a program you declare the variable. This means you give it a name and specify the data type. You may decide to not give it a value at that point in the program and give it a value later on, or you may decide to initialise the variable with a value (that can also be changed later). In the example above, the variable is declared and given an initial value all in one line of code.

Sample code

The sample code below shows a variable called ‘message’ being declared and given a value of “Hello”. The value is displayed on the screen to the user. Then, the value is changed to “Hello there” and this is displayed as output on the screen. Lastly, the message is displayed and the text “friend.” is added on the end when displayed as output so that the message being displayed is “Hello there friend.”. This is an example of concatenation (a fancy word for joining) where two strings are joined together.

You might notice that some lines of code that begin with two // forward slashes. These are comments in the code explaining what is going on. Comments are not carried out as instructions in the code but are used to annotate your code with explanations of what the code is meant to do, or you can also use them to add information about the author of the code, the program’s purpose or when it was created/modified.

package myjavaproject;

public class CreatingVariables {
    public static void main (String[] args){
        String message = "Hello"; // create and initialise String variable
        System.out.println(message);  // output variable value
        message = "Hello there"; // modify variable value
        System.out.println(message); // output modified variable value
        System.out.println(message + " friend.");  // concatenate strings
    }
}

Generating unique IDs and random strings in PHP

PHP functions covered in this tutorial:

  • uniqid()
  • md5()

This tutorial explains how to create unique ID strings using the uniqid() function and random strings using the md5() function. Warning: The uniqid() function does not create random or unpredictable strings. The uniqid() function should not be used for security purposes. For this purpose, it is better to use a secure string function or create a hash instead. You can create different types of hashes such as md5, sha1 or sha256. We will just look at the md5 hash in this tutorial.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code:

<?php
  // Warning: The uniqid() function does not create random or unpredictable strings.
  // The uniqid() function should not be used for security purposes. Use a secure
  // string function instead.

  echo uniqid(); // generates unique ID
  echo '<br>';
  echo uniqid('id'); // generates unique ID with prefix of 'id'
  echo '<br>';
  echo uniqid('id',true); // generates unique ID with prefix of 'id' and increased entropy
  echo '<br>';
  echo md5(time() . mt_rand(1,1000000)); // using md5 to create random string
?>

Array implode and explode functions in PHP

This tutorial shows how to use the implode and explode functions on arrays in PHP. The implode function is used to turn an array into a string, whereas the explode function is used to turn a string into an array. Watch the video below and then scroll down to see the commented sample code.

Sample PHP code:

<?php
  $avengers = array("Iron Man","Thor","Hulk","Hawkeye","Black Widow");
  // implode - turns an array into a string
  $avengersString = implode(' ',$avengers);
  // implode(' ',$avengers); will add a space between each array item in the new string

  echo $avengersString; // displays the string

  // explode - turns a string into an array
  $superheroesString = "wolverine,batman,hulk,spider-man,storm,iron man";
  $superheroesArray = explode(',',$superheroesString);
  // explode(',',$superheroesString); will add each item occuring after a comma in
  // the string as a separate element in the array.

  echo $superheroesArray[5]; //displays the 6th element in the array
?>

PHP string functions – substr_replace and str_replace

This tutorial explains how to use the substr_replace function to replace part of a string with something else. It also explains how to use the str_replace function to replace multiple occurrences of a portion of a string with another string value. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // substr_replace() replaces part of a string with something else
  $mystring = "The quick brown dog jumps over the lazy dog";
  echo substr_replace($mystring,"cat",16,3) , "</br>";

  // str_replace() replaces occurrences of a portion of a string with another value
  echo str_replace("dog","rat",$mystring);
?>

 

PHP string functions – strtolower and strtoupper

This tutorial explains how to convert strings to uppercase and lowercase using the strtolower and strtoupper functions. These functions each take one argument – the string that needs to be converted to lowercase or uppercase.

Example:

$uppercaseString = strtoupper($lowercaseString);

Watch the video below and then scroll down for the sample code.

PHP sample code:

<?php
  $mystring = "Hello world";
  
  // convert to uppercase
  $mystring_upper = strtoupper($mystring);

  // convert to lowercase
  $mystring_lower = strtolower($mystring);

  echo $mystring , "</br>";
  echo $mystring_upper , "</br>";
  echo $mystring_lower;
?>

PHP string functions – substr

The substr function is used to extract a portion of a string from a larger string. For example, substr can be used to extract a word from a sentence. This tutorial also shows how to combine the substr function with the strpos and strlen functions. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  $mystring = "The quick brown fox jumps over the lazy dog";
  $find = "dog";
  $start = strpos($mystring,$find);
  $stop = strlen($find);

  // will extract the word 'dog' from the string
  echo substr($mystring,$start,$stop) , "</br>";
  
  // will display each letter from the string on a new line
  $mystring_length = strlen($mystring);
  for($i=0;$i<$mystring_length;$i++){
    echo substr($mystring,$i,1),'</br>';
  }
?>

PHP string functions – strpos

In this tutorial you will learn how to use the strpos function to find occurrences of a string within another string and then return the position (index) of an occurrence of that string. For example, you could find a specific word in a sentence and then where that word is located in the sentence.

You can also specify an optional offset parameter which specifies where you want to start searching from within the string you are searching. Watch the video below and then scroll down to see the sample PHP code for the strpos function.

Sample PHP code:

1
2
3
4
5
6
7
8
9
10
<?php
 $string = "The quick brown fox jumps over the lazy dog.";
 $word = "fox";
 // strpos(string you want to look in, string you want to find, offset - where you
 // want to start looking from, optional, can be used if multiple occurences
 // of the target string in the string you are searching)
 // eg. strpos("string", "word", 4) where 4 is the offset.
 
 echo strpos($string,$word);
?>

PHP Manual references:

String length in PHP

This tutorial covers a few things about strings in PHP:

  • the index of strings (each character has an index number)
  • how to find the length of a string (how many characters there are in a string)
  • how to ‘loop’ through each character of a string

Although this may not seem all that useful yet, being able to find the length of a string and process each character of a string is something that will become very useful later on.

Indexing and strings

In every string, each character has what is known as an index or index number. In PHP, indexing starts from the number 0. That means that the letter B in the word “Batman” has an index of 0, the second letter “a” will have an index of 1, the third letter “t” will have an index of 2 and so on… The image below shows an example of this.

strings
A string’s index.

You might, as an example, want to find out what the third character is in a string. You could do this by using its index number eg. $mystring[2]; would return the third character in the string.

Finding the length of a string

The length of a string is how many characters are in the string. The word “Batman” has 6 letters in it so its length is 6. Letters, numbers, spaces and other characters are all counted in a string. So the string “Hello world” will have a string length of 11 because there are 10 letters and 1 space in it.

As an example, finding the length of a string might be useful if you want to check how much text was entered into a form (eg. checking that a minimum of 10 characters was used for a password, or a maximum of 160 characters were used for a tweet). The strlen() function is used to find the length of a string. Eg.  strlen(“my string”); will return the length of a string. We will look at other string functions later on.

Looping through strings

A for loop can be used to go through every single character in a string and process it. In the video example, we do this to display every letter of a string on a new line. This example might not be all that useful, but there are many other ways that a for loop can be used to process characters in a string.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code for displaying the length of a string:

1
2
3
4
5
6
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 echo $nameLength;
 }
?>

Sample PHP code for displaying the third character in a string:

1
2
3
4
5
<?php
 $name = "Batman";
 echo $name[2];
 }
?>

Sample PHP code for looping through a string:

1
2
3
4
5
6
7
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 for($i=0;$i<$nameLength;$i++){
 echo $name[$i] , '</br>';
 }
?>

PHP Manual references:

Data types in PHP

This tutorial explains the range of data types that can be used in PHP including:

  • String (letters, numbers and other characters – stored inside quotation marks)
  • Integer (whole positive or negative numbers)
  • Float (positive or negative real numbers – numbers with decimal place)
  • Boolean (can be only one of two possible values – either true or false)
  • NULL (no value / nothing)

String values are always stored inside quotation marks (can be double or single quotation marks, but they must match) eg. $mySentence = “Hello world”;

Integer, float and boolean values are not contained inside quotation marks eg. myNumber = 5;

It is important to note that when working with numbers, if you intend to treat a value as a number (and it will be used for numeric comparisons and calculations) such as a score in a game, then it should be in the form of an integer or float and not stored inside quotation marks. However, if a number value is not going to be used for calculations eg. a phone number or ZIP code, then it can be stored as a string value inside quotation marks.

Watch the video below and scroll down to see the sample code.

PHP sample code:

<?php
 $name = "Batman"; // strings (letters, numbers and other characters)
 $age = 25; // integers (whole positive or negative numbers - no decimal places)
 $num = 30.256; // floats (positive or negative real numbers - can have decimal place)
 $myboolean = true; // Boolean (only one of two possible values - true or false)
 $myvariable = NULL; // NULL (no value / nothing)
?>

PHP Manual references:

Data Types

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

You can watch the video about variables and data types here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Variables and Data Types in JavaScript

In this second video from the beginners JavaScript tutorial series, you will learn how to create variables and work with strings, integers, and float data types in JavaScript.

Variables are used to store information in program such as text, numbers or true/false values. Variables are given a name and are assigned a value. To create a variable in JavaScript we use the var keyword, then specify the variable name, use the = sign to assign a value, and then specify the value to store (you can also create a variable without immediately assigning it a value). For example: var myNumber = 50;

Variable names must be unique and cannot contain spaces. They don’t begin with a number but can contain numbers. They generally begin with a lowercase letter and if the variable name contains multiple words, then they can be indicated by using camelcase (starting each new word with an uppercase letter) eg. myVariable.

Variables can store data of different types. The main types are:

  • string – text including letters, numbers and other special characters eg. “Hello world”
  • integer – whole number values eg. 5
  • float – numbers with a decimal point eg. 5.3
  • boolean – a true or false value

Watch the video below or click here to view it on YouTube.

The code snippet below shows how to declare variables in JavaScript and how to assign values to a variable. Pay attention to the //comments which explain the different ways of setting up variables.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variables</title>
 <script type="text/javascript">
 
 var myVariable = 50;
 
 // Variable names (identifiers) have to begin with lower or uppercase letters or an underscore
 // Variable names cannot begin with a number, however they can contain a number
 // To declare a variable, use the keyword var
 // You can assign a value to a variable when you declare it, in one line (as above)
 // ...or you can declare a variable and then assign a value later, as below...
 
 var myVariable2;
 myVariable2 = "Hello there";
 
 document.write(myVariable);
 // This displays the value of myVariable in the browser window
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). Boolean is another data type which is used for true/false values. You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Hint: Have a look at the toFixed() method if you wish to display floats with a specified number of decimal places.

Next tutorial: Operators