+ 1
Can you give me example on how to count character in string using loop?
Thanks!!
9 Réponses
+ 6
Strings are fundamentally arrays of chars, therefore, it's very easy to iterate through them to calculate their length.
Example with a for loop:
int c = 0;
string calcLength = Console.ReadLine();
for (; c < calcLength; c++)
{
}
//now counter contains the length of the string.
It is very easy to do with a while loop as well, and even a foreach loop.
+ 4
If what you're interested in is a way to do it without using the string.Length property, here's another way without it.
int cc = 0;
string ccL = Console.ReadLine();
try
{
for (; true; cc++)
{
if (ccL[cc] == null);
}
}
catch
{
}
Console.WriteLine(cc);
The condition inside the try block doesn't mean anything, I couldn't use use an assignment statement (because strings are immutable), so I used it to throw the IndexOutOfBounds exception whenever the Index doesn't exist, so don't let it bother you, if you're puzzled by it.
+ 4
counting the charecters is the easiest thing in javascript but i will preffer try it in other prograi g language like in php and them try to implement it because in php it is more easier compared to javascript
+ 2
building off the knowledge of the previous answers I guess you could do
----------------------------------------------------
string word = Console.ReadLine;
int wordLength;
for (int i = word.length; i > 0; --i){
++wordLength;
}
simplest way I can think of doing it. but at the same time your essentially doing 'int wordlength = word.Length' which I'm assuming you are trying to avoid doing. But just thought I would point it out for anyone else reading so they could put everything together with all the answers provided.
just a note. you don't even need to store the length in a integer variable if you are not going to us it for anything. just use Console.WriteLine(word.Length); and your golden
+ 2
You can use foreach
int length = 0;
string str = "My String";
foreach (char ch in str)
{
length++;
}
+ 1
//c++
#include<sstream>
//string is s
istringsream sin(s)
char c;
while(sin>>c)count++;
//cnt=s.size()
+ 1
I think its easy if I use foreach. Thanks for the help!!
0
i doesn't know
0
function stringLength(sting){ let i = 0; while( sting.slice(i) !== '' ){ i++; } return i;}let sentence ="sting lenght";console.log(stringLength(sentence))
You can check this for word count