Как посчитать количество символов в массиве c

от admin

Найти длину массива в C#

В этом посте мы обсудим, как найти длину массива в C#.

1. Использование Array.Length Имущество

Стандартным решением для нахождения длины массива является использование Array.Length имущество. Он возвращает общее количество элементов, содержащихся в массиве. Если массив пуст, возвращается ноль. Следующий пример демонстрирует это:

результат:

Length is 5

Для многомерных массивов Array.Length возвращает общее количество элементов во всех измерениях. Другими словами, он возвращает сумму общего количества элементов в каждом измерении многомерного массива.

результат:

Length is 6

В C#, зубчатый массив могут быть разных размеров и размеров. Для зубчатого массива Length свойство будет указывать количество измерений в массиве. Например,

Подсчитать количество символов в массиве строк в C

Я пытаюсь подсчитать общее количество символов, исключая пробелы, в (что я считаю) указатель на массив строк, называемый myArray.

Я изо всех сил пытаюсь понять, что не так. Любая помощь приветствуется!

Пожеланная выходная мощность:

2 ответа

Баскетбольная версия, для иллюстрации низкого уровня:

Есть несколько проблем с этим вопросом, большинство из которых решаются ответом Шверна. Я расскажу еще кое-что, в том числе вопрос в исходном вопросе о том, как не считать пробелы:

Чтобы повторить, массивы C индексируются 0.

Возможно, вам нужен неограниченный цикл, чтобы вы могли добавить больше элементов в ваш массив без изменения кода (и число 1000 запутывает решение). В этот момент максимальное значение x становится sizeof(myArray) / sizeof(myArray[0]) , количество элементов. Вы также можете позволить компилятору решить, какой размер создать массив, удалив 1000 из определения myArray : char *myArray[] = <"Oh! ", "Hello ", "world.">;

Цикл верхнего уровня считает длину строки полной строки, но вам нужны только непробельные символы. Есть много способов сделать это, но самый простой способ — просто посчитать непробельные символы во вложенном цикле.

Учитывая эти вещи, следующий код получает желаемый результат:

Затем запустите его:

И это должно вывести:

Учитывая вычисление arrayLength , теперь мы можем добавить слово к myArray и увидеть, что результат изменяется с ожиданием:

Поскольку есть только 4 непробельных символа ( test ), это должно вывести:

Array Size (Length) in C#

How can I determine size of an array (length / number of items) in C#?

9 Answers 9

If it’s a one-dimensional array a ,

will give the number of elements of a .

If b is a rectangular multi-dimensional array (for example, int[,] b = new int[3, 5]; )

will give the number of dimensions (2) and

will get the length of any given dimension (0-based indexing for the dimensions — so b.GetLength(0) is 3 and b.GetLength(1) is 5).

As @Lucero points out in the comments, there is a concept of a «jagged array», which is really nothing more than a single-dimensional array of (typically single-dimensional) arrays.

For example, one could have the following:

Note that the 3 members of c all have different lengths. In this case, as before c.Length will indicate the number of elements of c , (3) and c[0].Length , c[1].Length , and c[2].Length will be 3, 2, and 7, respectively.

You can look at the documentation for Array to find out the answer to this question.

In this particular case you probably need Length:

But since this is such a basic question and you no doubt have many more like this, rather than just telling you the answer I’d rather tell you how to find the answer yourself.

Visual Studio Intellisense

When you type the name of a variable and press the . key it shows you a list of all the methods, properties, events, etc. available on that object. When you highlight a member it gives you a brief description of what it does.

Press F1

If you find a method or property that might do what you want but you’re not sure, you can move the cursor over it and press F1 to get help. Here you get a much more detailed description plus links to related information.

Search

The search terms size of array in C# gives many links that tells you the answer to your question and much more. One of the most important skills a programmer must learn is how to find information. It is often faster to find the answer yourself, especially if the same question has been asked before.

Читать:
Как двд диск перевести в ави

Use a tutorial

If you are just beginning to learn C# you will find it easier to follow a tutorial. I can recommend the C# tutorials on MSDN. If you want a book, I’d recommend Essential C#.

Stack Overflow

If you’re not able to find the answer on your own, please feel free to post the question on Stack Overflow. But we appreciate it if you show that you have taken the effort to find the answer yourself first.

for 1 dimensional array

for multidimensional array

To get the size of 1 dimension

gnivler's user avatar

With the Length property.

For a single dimension array, you use the Length property:

For multiple dimension arrays the Length property returns the total number of items in the array. You can use the GetLength method to get the size of one of the dimensions:

In most of the general cases ‘Length’ and ‘Count’ are used.

Typed List Array:

it goes like this: 1D:

then as you use this array :

or You can declare something like a matrix

What has been missed so far is what I suddenly was irritated about:

How do I know the amount of items inside the array? Is .Length equal .Count of a List?

The answer is: the amount of items of type X which have been put into an array of type X created with new X[number] you have to carry yourself!

Eg. using a counter: int countItemsInArray = 0 and countItemsInArray++ for every assignment to your array.

(The array just created with new X[number] has all space for number items (references) of type X already allocated, you can assign to any place inside as your first assignment, for example (if number = 100 and the variable name = a ) a[50] = new X(); .

I don’t know whether C# specifies the initial value of each place inside an array upon creation, if it doesn’t or the initial value you cannot compare to (because it might be a value you yourself have put into the array), you would have to track which places inside the array you already assigned to too if you don’t assign sequentially starting from 0 (in which case all places smaller than countItemsInArray would be assigned to).)

In your question size of an array (length / number of items) depending on whether / is meant to stand for «alternative» or «divide by» the latter still has to be covered (the «number of items» I just gave as «amount of items» and others gave .Length which corresponds to the value of number in my code above):

C# has a sizeof operator (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof). It’s safe to use for built-in types (such as int) (and only operates on types (not variables)). Thus the size of an array b of type int in bytes would be b.Length * sizeof(int) .

(Due to all space of an array already being allocated on creation, like mentioned above, and sizeof only working on types, no code like sizeof(variable)/sizeof(type) would work or yield the amount of items without tracking.)

Подсчитайте количество символов и слов в массиве

Как подсчитать количество символов и слов в массиве на С#?

должен возвращать 5 как количество слов и 18 (пробел считается как символ) как количество символов.

задан 22 мая ’11, 10:05

Это строка, а не массив целых чисел. — BoltClock♦

это правильно!. Вопрос обновлен — xorpower

2 ответы

Вы не можете напрямую назначить строку массиву целых чисел/символов в С#

ответ дан 22 мая ’11, 14:05

Вот пример, использующий LINQ для тривиального (на основе пробелов) подсчета слов:

Обычно это работает лучше, чем Split() call, потому что он обрабатывает строку как перечисляемый поток символов и просто считает по ходу, а не создает массив строк для хранения слов.

ответ дан 22 мая ’11, 15:05

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c# .net visual-studio arrays or задайте свой вопрос.

Похожие статьи