Заблокирован |
|
1 |
|
определение сколько символов/чисел в массиве14.08.2012, 14:16. Показов 8947. Ответов 10
сабж. как определить сколько в введёном массиве всего символов/букв/абрыкадабры
0 |
113 / 113 / 42 Регистрация: 02.05.2012 Сообщений: 524 Записей в блоге: 1 |
|
14.08.2012, 14:17 |
2 |
если все по отдельности предлагаю использовать наборы(set) для цифр и символов, все остальное будут буквы
0 |
Каратель 6608 / 4027 / 401 Регистрация: 26.03.2010 Сообщений: 9,273 Записей в блоге: 1 |
|
14.08.2012, 14:17 |
3 |
2 |
DiffEreD 1456 / 793 / 257 Регистрация: 21.06.2011 Сообщений: 1,740 Записей в блоге: 2 |
||||
14.08.2012, 16:32 |
4 |
|||
0 |
xEtr1k 9 / 9 / 5 Регистрация: 09.08.2012 Сообщений: 63 |
||||
15.08.2012, 01:56 |
5 |
|||
0 |
Mиxaил 541 / 446 / 162 Регистрация: 10.12.2009 Сообщений: 1,857 |
||||
15.08.2012, 02:40 |
6 |
|||
или
0 |
alsav22 5496 / 4891 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
||||
15.08.2012, 03:44 |
7 |
|||
0 |
Nameless One 5827 / 3478 / 358 Регистрация: 08.02.2010 Сообщений: 7,448 |
||||
15.08.2012, 07:22 |
8 |
|||
или
в общем случае не работает
0 |
60 / 60 / 7 Регистрация: 16.05.2010 Сообщений: 632 |
|
15.08.2012, 10:48 |
9 |
или Не по теме: можете объяснить,как это поможет определить нужное кол-во,ведь sizeof возвращает количество байт в массие char
0 |
5827 / 3478 / 358 Регистрация: 08.02.2010 Сообщений: 7,448 |
|
15.08.2012, 10:54 |
10 |
ведь sizeof возвращает количество байт в массие char только для статического массива, определенного глобально либо в той же функции, где вызывается оператор sizeof. Во всех остальных случаях он вернет размер char*.
1 |
60 / 60 / 7 Регистрация: 16.05.2010 Сообщений: 632 |
|
15.08.2012, 10:55 |
11 |
спасибо
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
15.08.2012, 10:55 |
11 |
Well, 11 years later, I run into this issue with a college assignment. The solution I found, worked without having to alter the function signatures that the assignment was asking for.
In my case, I had to make a function that returns the item index if the item existed or depending on if the itemPrefix (e.g. ‘B’ for Banana) already exists or not in the character array itemPrefixes to avoid passing duplicate prefixes.
So, I had to use a for
loop (or while
loop). The problem was that the assignment had given me specific signatures for each function and for that specific function it didn’t allow me to pass the count
variable that was on the main()
function as an argument.
I had to improvise.
Both the ways mentioned above didn’t work. strlen()
didn’t work as intended since there was not a ''
end character that strings have. The sizeof()
method also didn’t work, because it returned the size of the pointer of the character array that was passed in as an argument instead of the number of elements.
So, this is the function I came up with. A simple while loop that checks whether the current character is NULL
(or 0
).
void charArrLength(char array[]) {
int arrLength = 0;
while (array[arrLength] != 0) {
arrLength++; //increment by 1
}
printf("Character array has %d elements", arrLength);
}
For this to work though, in the main()
function, you need to declare your character array as a character pointer and then allocate the memory that you need based on the number of items that you ultimately wish to have inside your array.
void charArrLength(char array[]) {
int arrLength = 0;
while (array[arrLength] != 0) {
arrLength++;
}
printf("Character array has %d elements", arrLength); //should give 33
}
int main() {
char *array; //declare array as a pointer
int arraySize = 33; //can be anything
array = (char*) malloc(arraySize * sizeof(char));
charArrLength(array);
free(array); //free the previously allocated memory
}
Below you will see how I utilised this function in my assignment.
First, here is the above function tailored to my needs.
int isItemExists(char itemPrefixes[], char itemPrefix) {
int count = 0; //declare count variable and set to 0
int itemIndex = -1; //declare item index variable and set it to -1 as default
while (itemPrefixes[count] != 0) {
count++;
}
for (int i = 0; i < count; i++) {
if (itemPrefix == itemPrefixes[i]) {
itemIndex = i; //if item exists, set item index to i
}
}
return itemIndex;
}
Then, how I declared the itemPrefixes
array in main()
function and how I allocated the needed memory based on n
(the number of items the user would like to add to itemPrefixes
array).
char *itemPrefixes;
int n = 0; //number of items to be added variable
printf("> Enter how many items to add: ");
scanf("%d", &n);
//allocate n * size of char data type bytes of memory
itemPrefixes = (char*) malloc(n * sizeof(char));
And finally, here is how that function was used after all.
do {
printf("nn> Enter prefix for item %d: ", i + 1);
scanf(" %c", &itemPrefix);
//prompt the user if that itemPrefix already exists
if (isItemExists(itemPrefixes, itemPrefix) != -1) {
printf("nItem prefix already exists! Try another one.n");
}
} while (isItemExists(itemPrefixes, itemPrefix) != -1);
Also, in the end of the code I free the previously allocated memory.
free(itemPrefixes);
To clear this out, again, this could be much easier if the conditions were different. The assignment was strict about not passing n
as an argument. Nevertheless, I hope I help someone else that might be looking for this in the future!
Just for the sake of it, if anybody sees this and has something simpler to suggest, feel free to tell me.
А где return у стрелочной функции?
var gs = ['ddfg', 'dgfs'];
var jss = gs.map((far) => {
return far.length;
});
console.log(jss)
ну, или вот такvar jss = gs.map((far) => far.length);
а вообще, при помощи map не считают сумму, вам нужен reduce
var gs = ['ddfg', 'dgfs'];
var jss = gs.reduce((res, far) => res + far.length, 0)
console.log(jss)
UPD: а, ну или, при условии, что у вас маленькие массивы, можно написать такconst sum = ['ddfg', 'dgfs'].join('').length;
(PHP 4, PHP 5, PHP 7, PHP
strlen — Возвращает длину строки
Описание
strlen(string $string
): int
Список параметров
-
string
-
Строка (string), для которой измеряется длина.
Возвращаемые значения
Функция возвращает длину строки string
в байтах.
Примеры
Пример #1 Пример использования strlen()
<?php
$str = 'abcdef';
echo strlen($str); // 6$str = ' ab cd ';
echo strlen($str); // 7
?>
Примечания
Замечание:
Функция strlen() возвратит количество байт, а не число символов
в строке.
Смотрите также
- count() — Подсчитывает количество элементов массива или Countable объекте
- grapheme_strlen() — Получает длину строки в единицах графемы
- iconv_strlen() — Возвращает количество символов в строке
- mb_strlen() — Получает длину строки
rm dot nasir at hotmail dot com ¶
7 years ago
I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().
Example:
<?php
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = "السلام علیکم ورحمة الله وبرکاته!";var_export( strlen($utf8) ); // 59
echo "<br>";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>
Daniel Klein ¶
7 months ago
Since PHP 8.0, passing null to strlen() is deprecated. To check for a blank string (not including '0'):
<?php
// PHP < 8.0
if (!strlen($text)) {
echo 'Blank';
}// PHP >= 8.0
if ($text === null || $text === '')) {
echo 'empty';
}
joeri at sebrechts dot net ¶
6 years ago
When checking for length to make sure a value will fit in a database field, be mindful of using the right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).
<?php
// ok if php.ini default_charset set to UTF-8 (= default value)
mb_strlen($value);
iconv_strlen($value);
// always ok
mb_strlen($value, "UTF-8");
iconv_strlen($value, "UTF-8");// BAD, do not use:
strlen(utf8_decode($value)); // breaks for some multi-byte characters
grapheme_strlen($value); // counts graphemes, not code points
?>
2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))
<?php
// ok, but assumes mbstring.func_overload is 0 in php.ini (= default value)
strlen($value);
// ok, forces count in bytes
mb_strlen($value, "8bit")
?>
3. The database column is in another character set (UTF-16, ISO-8859-1, etc...) with a length defined in characters / code points.
Find the character set used, and pass it explicitly to the length function.
<?php
// ok, supported charsets: http://php.net/manual/en/mbstring.supported-encodings.php
mb_strlen($value, $charset);
// ok, supported charsets: https://www.gnu.org/software/libiconv/
iconv_strlen($value, $charset);
?>
jasonrohrer at fastmail dot fm ¶
9 years ago
PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('').
In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.
For example, in PHP:
strlen( "test" ) = 5
In C, the same call would return 2.
Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
basil at gohar dot us ¶
12 years ago
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3. Take the following code example:
<?php
$attributes
= array('one', 'two', 'three');
if (
strlen($attributes) == 0 && !is_bool($attributes)) {
echo "We are in the 'if'n"; // PHP 5.3
} else {
echo "We are in the 'else'n"; // PHP 5.2
}?>
This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array". In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):
"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."
So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5. This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:
strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028
If so, then you are likely experiencing this changed behavior.
vcardillo at gmail dot com ¶
10 years ago
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?
<?php
$foo = null;
$len = strlen(null);
$bar = '';
echo
"Length: " . strlen($foo) . "<br>";
echo "Length: $len <br>";
echo "Length: " . strlen(null) . "<br>";
if (
strlen($foo) === 0) echo 'Null length is Zero <br>';
if ($len === 0) echo 'Null length is still Zero <br>';
if (
strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';
if (
strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';
if (
strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';
if (
strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';
?>
// Begin Output:
Length: 0
Length: 0
Length: 0
Null length is Zero
Null length is still Zero
!is_null(): $foo is probably null
isset(): $foo is probably null
!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output
So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
John ¶
6 years ago
There's a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is "super slow". Well, that was probably true in old versions of PHP. But as of PHP7 that's definitely no longer true. It's now SUPER fast!
I created a 20,00,000 byte string (~20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.
The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn't get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation
So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!
Here is the complete benchmark code if you want to reproduce it on your machine:
<?php
$iterations
= 100000000; // 100 million
$str = str_repeat( '0', 20000000 );// benchmark loop and variable assignment to calculate loop overhead
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
$len = 0;
}
$end = microtime(true);
$loop_elapsed = 1000 * ($end - $start);// benchmark strlen in a loop
$len = 0;
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
$len = strlen( $str );
}
$end = microtime(true);
$strlen_elapsed = 1000 * ($end - $start);// subtract loop overhead from strlen() speed calculation
$strlen_elapsed -= $loop_elapsed;
echo
"nstring length: {$len}ntest took: {$strlen_elapsed} millisecondsn";?>
Как определить число букв в массиве?
Здравствуйте, у меня такая проблема. Мне нужно узнать число букв в массиве. Я пытался сначала найти число пробелов после слова, а потом вычесть его из количества символом максимально возможного массива. У меня выходит число пробелов = 0. Как сделать так, что бы выводило число букв в массиве?
Проблема усложняется тем, что строка может содержать символы unicode. буквы кириллицы, например. Чтобы их подсчитать, нужно определить длину символа по первому байту.
Считывание через >> в массив символов (да и в std::string тоже) идет до первого пробела.
Если вам нужна вся строка (со всеми пробелами, до символа переноса строки), используйте std::getline (и заодно замените массив символов на более удобный std::string ):
Кроме того, чтобы не считать символы вручную, можно использовать std::count и std::count_if :
Еще, пробелы можно считать через:
Тогда будут подсчитаны все «пробельные символы», куда кроме пробела входит табуляция и еще кое-что.
Я пытаюсь подсчитать общее количество символов, исключая пробелы, в (что я считаю) указатель на массив строк, называемый myArray.
Я изо всех сил пытаюсь понять, что не так. Любая помощь приветствуется!
Пожеланная выходная мощность:
2 ответа
Баскетбольная версия, для иллюстрации низкого уровня:
Есть несколько проблем с этим вопросом, большинство из которых решаются ответом Шверна. Я расскажу еще кое-что, в том числе вопрос в исходном вопросе о том, как не считать пробелы:
Чтобы повторить, массивы C индексируются 0.
Возможно, вам нужен неограниченный цикл, чтобы вы могли добавить больше элементов в ваш массив без изменения кода (и число 1000 запутывает решение). В этот момент максимальное значение x становится sizeof(myArray) / sizeof(myArray[0]) , количество элементов. Вы также можете позволить компилятору решить, какой размер создать массив, удалив 1000 из определения myArray : char *myArray[] = ;
Цикл верхнего уровня считает длину строки полной строки, но вам нужны только непробельные символы. Есть много способов сделать это, но самый простой способ — просто посчитать непробельные символы во вложенном цикле.
Учитывая эти вещи, следующий код получает желаемый результат:
Затем запустите его:
И это должно вывести:
Учитывая вычисление arrayLength , теперь мы можем добавить слово к myArray и увидеть, что результат изменяется с ожиданием:
Поскольку есть только 4 непробельных символа ( test ), это должно вывести:
Array. Length Свойство
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает общее число элементов во всех измерениях массива Array.
Значение свойства
Общее число элементов во всех измерениях массива Array; ноль, если в массиве нет элементов.
Исключения
Массив является многомерным и содержит больше элементов, чем задано в MaxValue.
Примеры
В следующем примере свойство используется Length для получения общего количества элементов в массиве. Он также использует GetUpperBound метод для определения количества элементов в каждом измерении многомерного массива.
Комментарии
Получение значения данного свойства является операцией порядка сложности O(1).