![]() |
Given a String, the task is to split the string by the delimiter. In this case, the delimiter is comma “,”. Examples: Input: apple,orange,banana Output: apple orange banana There are seven approaches to split the string, these are: Table of Content Using explode() FunctionThe explode() function splits a string into an array based on a specified delimiter (in this case, a comma). Example : In this example we plits a string into an array by commas and outputs each element of the array, one per line, using a loop.
Output apple orange banana Using preg_split() Function and Regular ExpressionThe preg_split() function with a regular expression to split the string into an array, providing more flexibility for complex delimiter patterns. Example: In this example we splits a string into an array using a regular expression to match commas, then outputs each element of the array in a loop.
Output apple orange banana Using strtok() FunctionThe strtok() function to tokenize the string based on a specified delimiter (comma in this case) iteratively until no more tokens are found. Example : in this example we tokenizes a string by commas using strtok, then outputs each token in a loop until no more tokens are found.
Output apple orange banana Using sscanf() FunctionUtilizes the sscanf() function with a format specifier to extract substrings separated by commas into separate variables, providing a structured way to split the string. Example: In this example we are using sscanf to split a comma-separated string into variables, then outputs each fruit on a new line.
Output apple orange banana Using substr() and strpos() FunctionsManually splits the string by using substr() and strpos() to extract substrings before and after each comma, allowing for custom handling of each part of the split string. Example : In this example we splits a comma-separated string using substr and strpos, assigns each part to a variable, and then outputs each fruit on a new line.
Output apple orange banana Using str_getcsv() FunctionThe str_getcsv() function is another way to split a string by a delimiter. This function is typically used to parse CSV data but can also be used for splitting strings based on a specified delimiter. Example: This method is particularly useful when working with data that follows a CSV format or when needing a robust solution for splitting strings by delimiters.
Output apple orange banana |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |