유용한 언어별 함수들

Sns format time Function

입력 문자열 / 출력 결과

입력

문자열: "2024-10-24T12:30:00"

출력 결과

n분전, 3일전 등

JavaScript


function timestamp_to_snstime(timestamp) {
    const now = new Date();
    const timeDiff = (now - new Date(timestamp)) / 1000; // seconds
    const minutes = Math.floor(timeDiff / 60);
    const hours = Math.floor(timeDiff / 3600);
    const days = Math.floor(timeDiff / 86400);
    const months = Math.floor(timeDiff / 2592000);
    
    if (minutes < 1) return "Just now";
    if (minutes < 60) return `${minutes} minutes ago`;
    if (hours < 24) return `${hours} hours ago`;
    if (days < 30) return `${days} days ago`;
    return `${months} months ago`;
}

console.log(timestamp_to_snstime('2024-10-24T12:30:00Z'));

            

Python


from datetime import datetime

def timestamp_to_snstime(timestamp):
    now = datetime.now()
    past = datetime.fromisoformat(timestamp)
    time_diff = now - past
    seconds = time_diff.total_seconds()
    minutes = seconds // 60
    hours = seconds // 3600
    days = seconds // 86400
    months = seconds // 2592000
    
    if minutes < 1:
        return "Just now"
    elif minutes < 60:
        return f"{int(minutes)} minutes ago"
    elif hours < 24:
        return f"{int(hours)} hours ago"
    elif days < 30:
        return f"{int(days)} days ago"
    else:
        return f"{int(months)} months ago"

print(timestamp_to_snstime('2024-10-24T12:30:00'))

            

Java


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimestampSNS {
    public static String timestamp_to_snstime(String timestamp) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime past = LocalDateTime.parse(timestamp, DateTimeFormatter.ISO_DATE_TIME);
        Duration duration = Duration.between(past, now);
        long minutes = duration.toMinutes();
        long hours = duration.toHours();
        long days = duration.toDays();
        long months = days / 30;
        
        if (minutes < 1) return "Just now";
        if (minutes < 60) return minutes + " minutes ago";
        if (hours < 24) return hours + " hours ago";
        if (days < 30) return days + " days ago";
        return months + " months ago";
    }

    public static void main(String[] args) {
        System.out.println(timestamp_to_snstime("2024-10-24T12:30:00"));
    }
}

            

C#


using System;

class TimestampSNS
{
    static string TimestampToSNS(string timestamp)
    {
        DateTime now = DateTime.Now;
        DateTime past = DateTime.Parse(timestamp);
        TimeSpan diff = now - past;

        double minutes = diff.TotalMinutes;
        double hours = diff.TotalHours;
        double days = diff.TotalDays;
        double months = days / 30;

        if (minutes < 1) return "Just now";
        if (minutes < 60) return $"{(int)minutes} minutes ago";
        if (hours < 24) return $"{(int)hours} hours ago";
        if (days < 30) return $"{(int)days} days ago";
        return $"{(int)months} months ago";
    }

    static void Main(string[] args)
    {
        Console.WriteLine(TimestampToSNS("2024-10-24T12:30:00"));
    }
}

            

C++


#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>

std::string timestamp_to_snstime(const std::string& timestamp) {
    std::tm tm = {};
    std::istringstream ss(timestamp);
    ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S");
    auto past_time = std::chrono::system_clock::from_time_t(std::mktime(&tm));
    auto now = std::chrono::system_clock::now();
    auto diff = std::chrono::duration_cast(now - past_time).count();
    
    long minutes = diff / 60;
    long hours = minutes / 60;
    long days = hours / 24;
    long months = days / 30;
    
    if (minutes < 1) return "Just now";
    if (minutes < 60) return std::to_string(minutes) + " minutes ago";
    if (hours < 24) return std::to_string(hours) + " hours ago";
    if (days < 30) return std::to_string(days) + " days ago";
    return std::to_string(months) + " months ago";
}

int main() {
    std::cout << timestamp_to_snstime("2024-10-24T12:30:00") << std::endl;
}

            

TypeScript


function timestamp_to_snstime(timestamp: string): string {
    const now = new Date();
    const past = new Date(timestamp);
    const diff = (now.getTime() - past.getTime()) / 1000; // seconds
    const minutes = Math.floor(diff / 60);
    const hours = Math.floor(diff / 3600);
    const days = Math.floor(diff / 86400);
    const months = Math.floor(diff / 2592000);
    
    if (minutes < 1) return "Just now";
    if (minutes < 60) return `${minutes} minutes ago`;
    if (hours < 24) return `${hours} hours ago`;
    if (days < 30) return `${days} days ago`;
    return `${months} months ago`;
}

console.log(timestamp_to_snstime('2024-10-24T12:30:00Z'));

            

PHP


function timestamp_to_snstime($timestamp) {
    $now = new DateTime();
    $past = new DateTime($timestamp);
    $diff = $now->diff($past);
    
    if ($diff->i < 1) return "Just now";
    if ($diff->i < 60) return $diff->i . " minutes ago";
    if ($diff->h < 24) return $diff->h . " hours ago";
    if ($diff->d < 30) return $diff->d . " days ago";
    return floor($diff->d / 30) . " months ago";
}

echo timestamp_to_snstime('2024-10-24T12:30:00');

            

Swift


import Foundation

func timestamp_to_snstime(timestamp: String) -> String {
    let now = Date()
    let formatter = ISO8601DateFormatter()
    guard let past = formatter.date(from: timestamp) else { return "Invalid date" }
    let diff = now.timeIntervalSince(past)
    
    let minutes = Int(diff / 60)
    let hours = minutes / 60
    let days = hours / 24
    let months = days / 30
    
    if minutes < 1 { return "Just now" }
    if minutes < 60 { return "\(minutes) minutes ago" }
    if hours < 24 { return "\(hours) hours ago" }
    if days < 30 { return "\(days) days ago" }
    return "\(months) months ago"
}

print(timestamp_to_snstime(timestamp: "2024-10-24T12:30:00"))

            

Kotlin


import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun timestamp_to_snstime(timestamp: String): String {
    val now = LocalDateTime.now()
    val past = LocalDateTime.parse(timestamp, DateTimeFormatter.ISO_DATE_TIME)
    val duration = Duration.between(past, now)
    
    val minutes = duration.toMinutes()
    val hours = duration.toHours()
    val days = duration.toDays()
    val months = days / 30
    
    return when {
        minutes < 1 -> "Just now"
        minutes < 60 -> "$minutes minutes ago"
        hours < 24 -> "$hours hours ago"
        days < 30 -> "$days days ago"
        else -> "$months months ago"
    }
}

fun main() {
    println(timestamp_to_snstime("2024-10-24T12:30:00"))
}

            

Go (Golang)


package main

import (
    "fmt"
    "time"
)

func timestamp_to_snstime(timestamp string) string {
    layout := "2006-01-02T15:04:05"
    past, err := time.Parse(layout, timestamp)
    if err != nil {
        return "Invalid date"
    }
    now := time.Now()
    diff := now.Sub(past)
    
    minutes := int(diff.Minutes())
    hours := int(diff.Hours())
    days := hours / 24
    months := days / 30

    switch {
    case minutes < 1:
        return "Just now"
    case minutes < 60:
        return fmt.Sprintf("%d minutes ago", minutes)
    case hours < 24:
        return fmt.Sprintf("%d hours ago", hours)
    case days < 30:
        return fmt.Sprintf("%d days ago", days)
    default:
        return fmt.Sprintf("%d months ago", months)
    }
}

func main() {
    fmt.Println(timestamp_to_snstime("2024-10-24T12:30:00"))
}

            

startsWith Function

입력 문자열 / 접두사 / 출력 결과

입력

문자열: "Hello, World!"
접두사: "Hello"

출력 결과

true

JavaScript


const str = "Hello, World!";
const prefix = "Hello";
const result = str.startsWith(prefix);
console.log(result); // true

        

Python


s = "Hello, World!"
prefix = "Hello"
result = s.startswith(prefix)
print(result)  # True

        

Java


public class StartsWithExample {
    public static void main(String[] args) {
        String s = "Hello, World!";
        String prefix = "Hello";
        boolean result = s.startsWith(prefix);
        System.out.println(result); // true
    }
}

        

C#


using System;

class StartsWithExample
{
    static void Main()
    {
        string s = "Hello, World!";
        string prefix = "Hello";
        bool result = s.StartsWith(prefix);
        Console.WriteLine(result); // True
    }
}

        

C++


#include <iostream>
#include <string>

// startsWith 함수 구현
bool startsWith(const std::string& str, const std::string& prefix) {
    if (prefix.size() > str.size()) return false;
    return std::equal(prefix.begin(), prefix.end(), str.begin());
}

int main() {
    std::string s = "Hello, World!";
    std::string prefix = "Hello";
    bool result = startsWith(s, prefix);
    std::cout << std::boolalpha << result << std::endl; // true
}

        

TypeScript


const str: string = "Hello, World!";
const prefix: string = "Hello";
const result: boolean = str.startsWith(prefix);
console.log(result); // true

        

PHP



function startsWith($string, $prefix) {
    return str_starts_with($string, $prefix);
}

$s = "Hello, World!";
$prefix = "Hello";
$result = startsWith($s, $prefix);
var_dump($result); // bool(true)


        

Swift


let s = "Hello, World!"
let prefix = "Hello"
let result = s.hasPrefix(prefix)
print(result) // true

        

Kotlin


fun main() {
    val s = "Hello, World!"
    val prefix = "Hello"
    val result = s.startsWith(prefix)
    println(result) // true
}

        

Go (Golang)


package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Hello, World!"
    prefix := "Hello"
    result := strings.HasPrefix(s, prefix)
    fmt.Println(result) // true
}

        

array_column Function

입력 배열 / 출력 열 값

입력

[
    { "id": 1, "name": "John" },
    { "id": 2, "name": "Jane" },
    { "id": 3, "name": "Doe" }
]

출력 결과

["John", "Jane", "Doe"]

JavaScript


// Using Array.prototype.map
const array = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Doe' }
];

const names = array.map(item => item.name);
console.log(names); // ["John", "Jane", "Doe"]

            

Python


array = [
    { "id": 1, "name": "John" },
    { "id": 2, "name": "Jane" },
    { "id": 3, "name": "Doe" }
]

names = [item['name'] for item in array]
print(names)  # ["John", "Jane", "Doe"]

            

Java


import java.util.*;
import java.util.stream.Collectors;

public class ArrayColumnExample {
    public static void main(String[] args) {
        List> array = new ArrayList<>();
        
        Map item1 = new HashMap<>();
        item1.put("id", 1);
        item1.put("name", "John");
        array.add(item1);
        
        Map item2 = new HashMap<>();
        item2.put("id", 2);
        item2.put("name", "Jane");
        array.add(item2);
        
        Map item3 = new HashMap<>();
        item3.put("id", 3);
        item3.put("name", "Doe");
        array.add(item3);
        
        List names = array.stream()
                                   .map(item -> (String) item.get("name"))
                                   .collect(Collectors.toList());
        
        System.out.println(names); // [John, Jane, Doe]
    }
}

            

C#


using System;
using System.Collections.Generic;
using System.Linq;

class ArrayColumnExample
{
    static void Main()
    {
        var array = new List>()
        {
            new Dictionary { { "id", 1 }, { "name", "John" } },
            new Dictionary { { "id", 2 }, { "name", "Jane" } },
            new Dictionary { { "id", 3 }, { "name", "Doe" } }
        };

        var names = array.Select(item => item["name"].ToString()).ToList();
        Console.WriteLine(string.Join(", ", names)); // John, Jane, Doe
    }
}

            

C++


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>

// Function to extract a column
std::vector array_column(const std::vector>& array, const std::string& key) {
    std::vector column;
    for (const auto& item : array) {
        auto it = item.find(key);
        if (it != item.end()) {
            column.push_back(it->second);
        }
    }
    return column;
}

int main() {
    std::vector> array = {
        { {"id", "1"}, {"name", "John"} },
        { {"id", "2"}, {"name", "Jane"} },
        { {"id", "3"}, {"name", "Doe"} }
    };

    std::vector names = array_column(array, "name");
    for(const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl; // John Jane Doe
    return 0;
}

            

TypeScript


// Using Array.prototype.map
const array = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Doe' }
];

const names = array.map(item => item.name);
console.log(names); // ["John", "Jane", "Doe"]

            

PHP


$array = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe']
];

$names = array_column($array, 'name');
print_r($names); // Array ( [0] => John [1] => Jane [2] => Doe )


            

Swift


let array: [[String: Any]] = [
    ["id": 1, "name": "John"],
    ["id": 2, "name": "Jane"],
    ["id": 3, "name": "Doe"]
]

let names = array.compactMap { $0["name"] as? String }
print(names) // ["John", "Jane", "Doe"]

            

Kotlin


data class Person(val id: Int, val name: String)

fun main() {
    val array = listOf(
        Person(1, "John"),
        Person(2, "Jane"),
        Person(3, "Doe")
    )

    val names = array.map { it.name }
    println(names) // [John, Jane, Doe]
}

            

Go (Golang)


package main

import (
    "fmt"
)

type Person struct {
    ID   int
    Name string
}

func main() {
    array := []Person{
        {ID: 1, Name: "John"},
        {ID: 2, Name: "Jane"},
        {ID: 3, Name: "Doe"},
    }

    var names []string
    for _, person := range array {
        names = append(names, person.Name)
    }

    fmt.Println(names) // [John Jane Doe]
}

            

file_exists Function

파일 경로 / 존재 여부 출력

입력

파일 경로: "/path/to/file.txt"

출력 결과

true

JavaScript (Node.js)


// Using fs.existsSync
const fs = require('fs');

const filePath = '/path/to/file.txt';
const exists = fs.existsSync(filePath);
console.log(exists); // true or false

            

Python


import os

file_path = '/path/to/file.txt'
exists = os.path.exists(file_path)
print(exists)  # True or False

            

Java


import java.nio.file.*;

public class FileExistsExample {
    public static void main(String[] args) {
        String filePath = "/path/to/file.txt";
        Path path = Paths.get(filePath);
        boolean exists = Files.exists(path);
        System.out.println(exists); // true or false
    }
}

            

C#


using System;
using System.IO;

class FileExistsExample
{
    static void Main()
    {
        string filePath = "/path/to/file.txt";
        bool exists = File.Exists(filePath);
        Console.WriteLine(exists); // True or False
    }
}

            

C++


#include <iostream>
#include <fstream>
#include <string>

// Function to check if a file exists
bool file_exists(const std::string& name) {
    std::ifstream f(name.c_str());
    return f.good();
}

int main() {
    std::string filePath = "/path/to/file.txt";
    bool exists = file_exists(filePath);
    std::cout << std::boolalpha << exists << std::endl; // true or false
    return 0;
}

            

TypeScript (Node.js)


// Using fs.existsSync
import * as fs from 'fs';

const filePath: string = '/path/to/file.txt';
const exists: boolean = fs.existsSync(filePath);
console.log(exists); // true or false

            

PHP


$filePath = '/path/to/file.txt';
$exists = file_exists($filePath);
var_dump($exists); // bool(true) or bool(false)

            

Swift


import Foundation

let filePath = "/path/to/file.txt"
let fileManager = FileManager.default
let exists = fileManager.fileExists(atPath: filePath)
print(exists) // true or false

            

Kotlin


import java.io.File

fun main() {
    val filePath = "/path/to/file.txt"
    val file = File(filePath)
    val exists = file.exists()
    println(exists) // true or false
}

            

Go (Golang)


package main

import (
    "fmt"
    "os"
)

func fileExists(filePath string) bool {
    _, err := os.Stat(filePath)
    return !os.IsNotExist(err)
}

func main() {
    filePath := "/path/to/file.txt"
    exists := fileExists(filePath)
    fmt.Println(exists) // true or false
}

            

str_replace Function

입력 문자열 / 검색 문자열 / 대체 문자열 / 출력 결과

입력

문자열: "Hello, World!"
검색 문자열: "World"
대체 문자열: "PHP"

출력 결과

"Hello, PHP!"

JavaScript


// Using String.prototype.replace
const str = "Hello, World!";
const search = "World";
const replace = "PHP";
const result = str.replace(search, replace);
console.log(result); // "Hello, PHP!"

            

Python


# Using str.replace()
s = "Hello, World!"
search = "World"
replace = "PHP"
result = s.replace(search, replace)
print(result)  # "Hello, PHP!"

            

Java


// Using String.replace()
public class StrReplaceExample {
    public static void main(String[] args) {
        String s = "Hello, World!";
        String search = "World";
        String replace = "PHP";
        String result = s.replace(search, replace);
        System.out.println(result); // "Hello, PHP!"
    }
}

            

C#


// Using String.Replace()
using System;

class StrReplaceExample
{
    static void Main()
    {
        string s = "Hello, World!";
        string search = "World";
        string replace = "PHP";
        string result = s.Replace(search, replace);
        Console.WriteLine(result); // "Hello, PHP!"
    }
}

            

C++


#include <iostream>
#include <string>

// Function to replace all occurrences of a substring
std::string str_replace_all(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
    return str;
}

int main() {
    std::string s = "Hello, World!";
    std::string search = "World";
    std::string replace = "PHP";
    std::string result = str_replace_all(s, search, replace);
    std::cout << result << std::endl; // "Hello, PHP!"
    return 0;
}

            

TypeScript


// Using String.prototype.replace
const str: string = "Hello, World!";
const search: string = "World";
const replace: string = "PHP";
const result: string = str.replace(search, replace);
console.log(result); // "Hello, PHP!"

            

PHP


$str = "Hello, World!";
$search = "World";
$replace = "PHP";
$result = str_replace($search, $replace, $str);
echo $result; // "Hello, PHP!"

            

Swift


// Using String.replacingOccurrences
let s = "Hello, World!"
let search = "World"
let replace = "PHP"
let result = s.replacingOccurrences(of: search, with: replace)
print(result) // "Hello, PHP!"

            

Kotlin


// Using String.replace()
fun main() {
    val s = "Hello, World!"
    val search = "World"
    val replace = "PHP"
    val result = s.replace(search, replace)
    println(result) // "Hello, PHP!"
}

            

Go (Golang)


package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Hello, World!"
    search := "World"
    replace := "PHP"
    result := strings.ReplaceAll(s, search, replace)
    fmt.Println(result) // "Hello, PHP!"
}

            

implode Function

입력 배열 / 구분자 / 출력 결과

입력

배열: ["Apple", "Banana", "Cherry"]
구분자: ", "

출력 결과

"Apple, Banana, Cherry"

JavaScript


// Using Array.prototype.join
const array = ["Apple", "Banana", "Cherry"];
const separator = ", ";
const result = array.join(separator);
console.log(result); // "Apple, Banana, Cherry"

        

Python


# Using str.join()
array = ["Apple", "Banana", "Cherry"]
separator = ", "
result = separator.join(array)
print(result)  # "Apple, Banana, Cherry"

        

Java


// Using String.join()
import java.util.Arrays;
import java.util.List;

public class ImplodeExample {
    public static void main(String[] args) {
        List array = Arrays.asList("Apple", "Banana", "Cherry");
        String separator = ", ";
        String result = String.join(separator, array);
        System.out.println(result); // "Apple, Banana, Cherry"
    }
}

        

C#


// Using String.Join()
using System;
using System.Collections.Generic;

class ImplodeExample
{
    static void Main()
    {
        List array = new List { "Apple", "Banana", "Cherry" };
        string separator = ", ";
        string result = String.Join(separator, array);
        Console.WriteLine(result); // "Apple, Banana, Cherry"
    }
}

        

C++


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

// Function to implode an array with a separator
std::string implode(const std::vector& array, const std::string& separator) {
    std::string result;
    for (size_t i = 0; i < array.size(); ++i) {
        result += array[i];
        if (i != array.size() - 1)
            result += separator;
    }
    return result;
}

int main() {
    std::vector array = { "Apple", "Banana", "Cherry" };
    std::string separator = ", ";
    std::string result = implode(array, separator);
    std::cout << result << std::endl; // "Apple, Banana, Cherry"
    return 0;
}

        

TypeScript


// Using Array.prototype.join
const array: string[] = ["Apple", "Banana", "Cherry"];
const separator: string = ", ";
const result: string = array.join(separator);
console.log(result); // "Apple, Banana, Cherry"

        

PHP



$array = ["Apple", "Banana", "Cherry"];
$separator = ", ";
$result = implode($separator, $array);
echo $result; // "Apple, Banana, Cherry"


        

Swift


// Using joined(separator:)
let array = ["Apple", "Banana", "Cherry"]
let separator = ", "
let result = array.joined(separator: separator)
print(result) // "Apple, Banana, Cherry"

        

Kotlin


// Using joinToString()
fun main() {
    val array = listOf("Apple", "Banana", "Cherry")
    val separator = ", "
    val result = array.joinToString(separator)
    println(result) // "Apple, Banana, Cherry"
}

        

Go (Golang)


package main

import (
    "fmt"
    "strings"
)

func main() {
    array := []string{"Apple", "Banana", "Cherry"}
    separator := ", "
    result := strings.Join(array, separator)
    fmt.Println(result) // "Apple, Banana, Cherry"
}

        

array_merge Function

입력 배열1, 배열2 / 출력 배열

입력

배열1: ["Apple", "Banana"]
배열2: ["Cherry", "Date"]

출력 결과

["Apple", "Banana", "Cherry", "Date"]

JavaScript


// Using Array.prototype.concat
const array1 = ["Apple", "Banana"];
const array2 = ["Cherry", "Date"];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // ["Apple", "Banana", "Cherry", "Date"]

// Using Spread Operator
const mergedArray2 = [...array1, ...array2];
console.log(mergedArray2); // ["Apple", "Banana", "Cherry", "Date"]

        

Python


# Using the + operator
array1 = ["Apple", "Banana"]
array2 = ["Cherry", "Date"]
merged_array = array1 + array2
print(merged_array)  # ["Apple", "Banana", "Cherry", "Date"]

# Using list.extend()
merged_array2 = array1.copy()
merged_array2.extend(array2)
print(merged_array2)  # ["Apple", "Banana", "Cherry", "Date"]

        

Java


// Using ArrayList and addAll
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayMergeExample {
    public static void main(String[] args) {
        List array1 = new ArrayList<>(Arrays.asList("Apple", "Banana"));
        List array2 = Arrays.asList("Cherry", "Date");
        
        List mergedArray = new ArrayList<>(array1);
        mergedArray.addAll(array2);
        
        System.out.println(mergedArray); // [Apple, Banana, Cherry, Date]
    }
}

        

C#


// Using List and AddRange
using System;
using System.Collections.Generic;

class ArrayMergeExample
{
    static void Main()
    {
        List array1 = new List { "Apple", "Banana" };
        List array2 = new List { "Cherry", "Date" };
        
        List mergedArray = new List(array1);
        mergedArray.AddRange(array2);
        
        Console.WriteLine(string.Join(", ", mergedArray)); // Apple, Banana, Cherry, Date
    }
}

        

C++


// Using std::vector and insert
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector array1 = { "Apple", "Banana" };
    std::vector array2 = { "Cherry", "Date" };
    
    std::vector mergedArray = array1;
    mergedArray.insert(mergedArray.end(), array2.begin(), array2.end());
    
    for(const auto& fruit : mergedArray) {
        std::cout << fruit << " ";
    }
    std::cout << std::endl; // Apple Banana Cherry Date
    return 0;
}

        

TypeScript


// Using Array.prototype.concat
const array1: string[] = ["Apple", "Banana"];
const array2: string[] = ["Cherry", "Date"];
const mergedArray: string[] = array1.concat(array2);
console.log(mergedArray); // ["Apple", "Banana", "Cherry", "Date"]

// Using Spread Operator
const mergedArray2: string[] = [...array1, ...array2];
console.log(mergedArray2); // ["Apple", "Banana", "Cherry", "Date"]

        

PHP



$array1 = ["Apple", "Banana"];
$array2 = ["Cherry", "Date"];
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray); // Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date )


        

Swift


// Using + operator
let array1 = ["Apple", "Banana"]
let array2 = ["Cherry", "Date"]
let mergedArray = array1 + array2
print(mergedArray) // ["Apple", "Banana", "Cherry", "Date"]

// Using append(contentsOf:)
var mergedArray2 = array1
mergedArray2.append(contentsOf: array2)
print(mergedArray2) // ["Apple", "Banana", "Cherry", "Date"]

        

Kotlin


// Using plus operator
val array1 = listOf("Apple", "Banana")
val array2 = listOf("Cherry", "Date")
val mergedArray = array1 + array2
println(mergedArray) // [Apple, Banana, Cherry, Date]

// Using flatMap
val mergedArray2 = listOf(array1, array2).flatten()
println(mergedArray2) // [Apple, Banana, Cherry, Date]

        

Go (Golang)


// Using append
package main

import (
    "fmt"
)

func main() {
    array1 := []string{"Apple", "Banana"}
    array2 := []string{"Cherry", "Date"}
    mergedArray := append(array1, array2...)
    fmt.Println(mergedArray) // [Apple Banana Cherry Date]
}