+ 1

Can you give me example on how to count character in string using loop?

Thanks!!

11th Jan 2017, 5:48 AM
Irah Singson
Irah Singson - avatar
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.
11th Jan 2017, 6:22 AM
Dao
Dao - avatar
+ 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.
11th Jan 2017, 6:58 AM
Dao
Dao - avatar
+ 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
12th Jan 2017, 4:54 AM
ARNAB BISWAS
ARNAB BISWAS - avatar
+ 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
11th Jan 2017, 3:50 PM
Henry Smallio
Henry Smallio - avatar
+ 2
You can use foreach int length = 0; string str = "My String"; foreach (char ch in str) { length++; }
11th Jan 2017, 8:39 PM
Umut Dağ
Umut Dağ - avatar
+ 1
//c++ #include<sstream> //string is s istringsream sin(s) char c; while(sin>>c)count++; //cnt=s.size()
11th Jan 2017, 7:44 AM
kerpoo
kerpoo - avatar
+ 1
I think its easy if I use foreach. Thanks for the help!!
11th Jan 2017, 11:38 PM
Irah Singson
Irah Singson - avatar
0
i doesn't know
13th Jan 2017, 8:55 AM
nyichay hell
nyichay hell - avatar
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
3rd Sep 2022, 7:17 AM
Ibrahim Khalil
Ibrahim Khalil - avatar