Substring is a commonly used function in programming that is used to extract a portion of a string. It is available in many programming languages and is used to manipulate strings efficiently. In this article
we will explore the substring function and how it can be used in various programming languages.
The substring function is used to extract a portion of a string starting at a specified position and ending at a specified position. It takes two arguments - the starting position and the length of the substring. The starting position is the index of the character where the substring should begin
and the length is the number of characters to extract.
Let's take a look at how the substring function works in some popular programming languages.
1. JavaScript:
In JavaScript
the substring function is used to extract a portion of a string. Here is an example of how it can be used:
```javascript
let str = "Hello
World!";
let substr = str.substring(7
5);
console.log(substr); // Output: World
```
In this example
the substring function is used to extract the word "World" from the string "Hello
World!" starting at index 7 and ending after 5 characters.
2. Python:
In Python
the substring function is not directly available like in JavaScript. Instead
string slicing is used to extract a portion of a string. Here is an example of how it can be done:
```python
str = "Hello
World!"
substr = str[7:12]
print(substr) # Output: World
```
In this example
string slicing is used to extract the word "World" from the string "Hello
World!" starting at index 7 and ending at index 12.
3. Java:
In Java
the substring function is available as a method of the String class. Here is an example of how it can be used:
```java
String str = "Hello
World!";
String substr = str.substring(7
12);
System.out.println(substr); // Output: World
```
In this example
the substring method is used to extract the word "World" from the string "Hello
World!" starting at index 7 and ending at index 12.
Overall
the substring function is a useful tool for manipulating strings in programming. It allows for the extraction of specific portions of a string
which can be useful in many different scenarios. Whether you are working in JavaScript
Python
Java
or any other programming language
the substring function can help you work with strings efficiently.