循环通过VB.NET中的字符串中的字符 [英] Looping through characters in a string in VB.NET

查看:858
本文介绍了循环通过VB.NET中的字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于处理过去的考试文件,以准备Visual Basic考试。我需要帮助下面的问题,我被困住。

I'm busy working on past exam papers in preparation for a Visual Basic exam. I need help with the following question which I'm stuck with.


编写函数过程来计算字符e,f和g出现在字符串中的次数

Write a function procedure to calculate the number of times the characters "e", "f" and "g" appears in a string

我试着写出伪代码,并得出以下结果。

I tried to write the psuedo code and came up with the following.

Loop through each individual character in the string
If the character = "e","f" or "g" add 1 to number of characters
Exit loop 
Display total in messagebox

如何循环字符串中的单个字符code> for loop)和如何计算特定字符出现在字符串中的次数?

How do I loop through individual characters in a string (using a for loop) and how do I count the number of times a specific character appears in a string?

推荐答案

答案很大程度上取决于你在课程中学到的内容,以及你应该使用哪些函数。

The answer greatly depends on what you’ve already learned in your course work and which functions you are supposed to use.

循环字符串中的字符就像这样:

But in general, looping over the characters in a string is as easy as this:

Dim s As String = "test"

For Each c As Char in s
    ' Count c
Next

对于计数,对于每个字符只需要单独的计数器变量( eCount As Integer 等),并在 c 等于该字符 - 显然,一旦增加要计数的字符数,该方法就不会很好地缩放。这可以通过维护相关字符的字典来解决,但我猜测这对你的练习来说太先进了。

As for counting, simply have separate counter variables (eCount As Integer etc.) for each character and increment them when c equals that character – obviously that approach doesn’t scale well once you increase the number of characters to count. This can be solved by maintaining a dictionary of the relevant characters but I’m guessing that this is too advanced for your exercise.

这篇关于循环通过VB.NET中的字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆