Как удалить запятую в конце массива java
Если вы хотите удалить запятую в конце массива при выводе его элементов, вы можете использовать цикл для итерации по всем элементам, кроме последнего, и добавить запятую после каждого элемента, кроме последнего. Затем вы можете вывести последний элемент массива без запятой.
int[] nums = 1, 2, 3, 4, 5>; StringBuilder sb = new StringBuilder(); for (int i = 0; i nums.length - 1; i++) sb.append(nums[i]).append(", "); > sb.append(nums[nums.length - 1]); String result = sb.toString(); System.out.println(result); // => 1, 2, 3, 4, 5
- В этом примере мы используем StringBuilder для создания строки, содержащей все элементы массива.
- Мы проходим по всем элементам массива, кроме последнего, и добавляем их в строку, разделяя запятой и пробелом.
- Затем мы добавляем последний элемент массива без запятой.
- Наконец, мы выводим строку на консоль.
Как вывести элементы массива через запятую
Профиль
Группа: Участник
Сообщений: 588
Регистрация: 20.4.2009
Репутация: нет
Всего: нет
есть массив @array; необходимо вывести все элементы через запятую. При этом запятая должна ставиться только между элементами массива, но никак не в начале или в конце.
Т.е. должно быть так:
Профиль
Группа: Участник
Сообщений: 312
Регистрация: 8.1.2007
Где: Ленобласть
Репутация: 3
Всего: 23
| Код |
| print join ‘,’, @array; |
| Код |
| local $, = ‘,’; print @array; |
| Код |
| local $» = ‘,’; print «@array»; |
implode
Альтернативная сигнатура (не поддерживается с именованными аргументами):
implode ( array $array ): string
Устаревшая сигнатура (устарела с PHP 7.4.0, удалена в PHP 8.0.0):
implode ( array $array , string $separator ): string
Объединяет элементы массива с помощью строки separator .
Список параметров
Необязательный. По умолчанию равен пустой строке.
Массив объединяемых строк.
Возвращаемые значения
Возвращает строку, содержащую строковое представление всех элементов массива в указанном порядке, с разделителем между каждым элементом.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | Передача separator после array больше не поддерживается. |
| 7.4.0 | Передача separator после array (т.е. использование недокументированного порядка параметров) устарела. |
Примеры
Пример #1 Пример использования implode()
$array = [ ‘имя’ , ‘почта’ , ‘телефон’ ];
var_dump ( implode ( «,» , $array )); // string(32) «имя,почта,телефон»
// Пустая строка при использовании пустого массива:
var_dump ( implode ( ‘привет’ , [])); // string(0) «»
// Параметр separator не обязателен:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
- explode() — Разбивает строку с помощью разделителя
- preg_split() — Разбивает строку по регулярному выражению
- http_build_query() — Генерирует URL-кодированную строку запроса
User Contributed Notes 14 notes
14 years ago
it should be noted that an array with one or no elements works fine. for example:
$a1 = array( «1» , «2» , «3» );
$a2 = array( «a» );
$a3 = array();
echo «a1 is: ‘» . implode ( «‘,'» , $a1 ). «‘
» ;
echo «a2 is: ‘» . implode ( «‘,'» , $a2 ). «‘
» ;
echo «a3 is: ‘» . implode ( «‘,'» , $a3 ). «‘
» ;
?>
will produce:
===========
a1 is: ‘1’,’2′,’3′
a2 is: ‘a’
a3 is: »
4 years ago
It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:
declare( strict_types = 1 );
$a = array( ‘one’ , ‘two’ , ‘three’ );
$b = array( ‘1st’ => ‘four’ , ‘five’ , ‘3rd’ => ‘six’ );
echo implode ( ‘,’ , $a ), ‘/’ , implode ( ‘,’ , $b );
?>
outputs:
one,two,three/four,five,six
10 years ago
Can also be used for building tags or complex lists, like the following:
$elements = array( ‘a’ , ‘b’ , ‘c’ );
- » . implode ( «
- » , $elements ) . «
?>
This is just an example, you can create a lot more just finding the right glue! 😉
7 years ago
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.
class Foo
protected $title ;
public function __construct ( $title )
$this -> title = $title ;
>
public function __toString ()
return $this -> title ;
>
>
$array = [
new Foo ( ‘foo’ ),
new Foo ( ‘bar’ ),
new Foo ( ‘qux’ )
];
echo implode ( ‘; ‘ , $array );
?>
will output:
12 years ago
If you want to implode an array of booleans, you will get a strange result:
var_dump ( implode ( » ,array( true , true , false , false , true )));
?>
Output:
string(3) «111»
TRUE became «1», FALSE became nothing.
3 years ago
If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.
function mapped_implode ( $glue , $array , $symbol = ‘=’ ) return implode ( $glue , array_map (
function( $k , $v ) use( $symbol ) <
return $k . $symbol . $v ;
>,
array_keys ( $array ),
array_values ( $array )
)
);
>
echo mapped_implode ( ‘, ‘ , $arr , ‘ is ‘ );
// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo
2 years ago
Sometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.
function wrap_implode ( $array , $before = » , $after = » , $separator = » ) if( ! $array ) return » ;
return $before . implode ( » < $after >< $separator > < $before >» , $array ) . $after ;
>
echo wrap_implode ([ ‘path’ , ‘to’ , ‘file.php’ ], ‘/’ );
// «/path/to/file.php»
$pattern = ‘#’ . wrap_implode ([ 4 , 2 , 2 ], ‘\d’ , ‘[-.]’ ) . ‘#’ ;
echo $pattern , «\n» ; // #\d[-.]\d[-.]\d#
echo preg_replace ( $pattern , ‘[REDACTED]’ , ‘The UFO appeared between 2012-12-24 and 2013.01.06 every night.’ );
// ‘The UFO appeared between [REDACTED] and [REDACTED] every night.
echo wrap_implode ([ ‘line’ , ‘by’ , ‘line’ ], ‘‘ , ‘‘ , ‘
‘ );
// line
by
line
10 years ago
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
var_dump ( implode ( ‘:’ , ‘xxxxx’ ));
?>
returns
NULL
This threw me for a little while.
11 years ago
Even handier if you use the following:
$id_nums = array( 1 , 6 , 12 , 18 , 24 );
$id_nums = implode ( «, » , $id_nums );
$sqlquery = «Select name,email,phone from usertable where user_id IN ( $id_nums )» ;
// $sqlquery becomes «Select name,email,phone from usertable where user_id IN (1,6,12,18,24)»
?>
Be sure to escape/sanitize/use prepared statements if you get the ids from users.
8 years ago
null values are imploded too. You can use array_filter() to sort out null values.
$ar = array( «hello» , null , «world» );
print( implode ( ‘,’ , $ar )); // hello,,world
print( implode ( ‘,’ , array_filter ( $ar , function( $v )< return $v !== null ; >))); // hello,world
?>
3 years ago
If you want to use a key inside array:
Example:
$arr=array(
array(«id» => 1,»name» => «Test1»),
array(«id» => 2,»name» => «Test2»),
);
echo implode_key(«,»,$arr, «name»);
OUTPUT: Test1, Test2
function implode_key($glue, $arr, $key) $arr2=array();
foreach($arr as $f) if(!isset($f[$key])) continue;
$arr2[]=$f[$key];
>
return implode($glue, $arr2);
>
6 years ago
It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.
$test = implode ([ «one» , 2 , 3 , «four» , 5.67 ]);
echo $test ;
//outputs: «one23four5.67»
?>
1 year ago
There is no mention of behavior on a empty array, so I tried it and here’s the result:
$ar = array();
$result = implode ( ‘,’ , $ar ); // Comma arbitrarily applied as the separator
$is_result_empty = empty( $result );
?>
$result:
$is_result_empty: 1
In other words, an empty string is the result.
3 years ago
* Join pieces with a string recursively .
*
* @ param mixed $glue String between pairs ( glue ) or an array pair ‘s glue and key/value glue or $pieces.
* @param iterable $pieces Pieces to implode (optional).
* @return string Joined string
*/
function double_implode($glue, iterable $pieces = null): string
$glue2 = null;
if ($pieces === null) $pieces = $glue;
$glue = »;
> elseif (is_array($glue)) list($glue, $glue2) = $glue;
>
?php
$result = [];
foreach ($pieces as $key => $value) $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
>
return implode($glue, $result);
>
?>
Examples:
$array = [‘ a ‘ => 1, ‘b’ => 2];
$str = implode($array);
$str = implode(‘ , ‘, $array);
$str = implode([‘» ‘, ‘ keyword»>, ‘, $iterator);
$str = implode([‘» ‘, ‘ foot»>+add a note
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
Array.prototype.join()
Метод join() объединяет все элементы массива (или массивоподобного объекта) в строку.
Интерактивный пример
Синтаксис
arr.join([separator])
Параметры
separator Необязательный
Определяет строку, разделяющую элементы массива. В случае необходимости тип разделителя приводится к типу Строка. Если он не задан, элементы массива разделяются запятой ‘,‘. Если разделитель — пустая строка, элементы массива ничем не разделяются в возвращаемой строке.
Возвращаемое значение
Строка, содержащая все элементы массива. Если arr.length == 0 , то будет возвращена пустая строка.
Описание
Преобразует все элементы массива в строки и объединяет их в одну большую строку. Элемент массива с типом undefined или null преобразуется в пустую строку.
Примеры
Соединение массива четырьмя различными способами
В следующем примере создаётся массив a с тремя элементами, затем они четыре раза объединяются в строку: с использованием разделителя по умолчанию, запятой с пробелом, плюса, окружённого пробелами, и пустой строки.
var a = ["Ветер", "Дождь", "Огонь"]; var myVar1 = a.join(); // присвоит 'Ветер,Дождь,Огонь' переменной myVar1 var myVar2 = a.join(", "); // присвоит 'Ветер, Дождь, Огонь' переменной myVar2 var myVar3 = a.join(" + "); // присвоит 'Ветер + Дождь + Огонь' переменной myVar3 var myVar4 = a.join(""); // присвоит 'ВетерДождьОгонь' переменной myVar4
Соединение элементов массивоподобного объекта
В следующем примере соединяется массивоподобный объект (в данном случае список аргументов функции) с использованием вызова Function.prototype.call для Array.prototype.join .
function f(a, b, c) var s = Array.prototype.join.call(arguments); console.log(s); // '1,a,true' > f(1, "a", true);
Спецификации
| Specification |
|---|
| ECMAScript Language Specification # sec-array.prototype.join |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
- String.prototype.split()
- Array.prototype.toString()
- TypedArray.prototype.join()
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 4 авг. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.