在C中解析字符串
仅使用 C
我想解析一个字符串并:
- 计算字符串中字符的出现次数(例如,计算传入字符串中的所有
'e'
) - 一次计数(甚至当我数数时)将 e 替换为 3
Using just C
I would like to parse a string and:
- count the occurrences of a character in a string (for example, count all the
'e'
s in a passed in string) - Once counted (or even as I am counting) replace the e's with 3's
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,你要么懒惰,要么卡住了,假设卡住了。
您需要一个具有类似签名的函数
在函数内部您需要
出现
字符串到
检查当前字符
charToFind,
发生并执行
replacement
出现次数
OK, you're either lazy, or stuck, assuming stuck.
You need a function with a signature something like
Inside the function you need
occurrences
the string to it's end
check is the current char the
charToFind,
occurrences and perform the
replacement
the count of occurrences
该函数将采用一个字符串,将每个“e”替换为“3”,并返回执行替换的次数。 它安全、干净、快捷。
This function will take a string, replace every 'e' with '3', and return the number of times it performed the substitution. It's safe, it's clean, it's fast.
这是一个帮助您入门的 shell。 如果您需要任何帮助,请在此询问。
Here's a shell to get you started. Ask here if you need any help.
一般来说,最好使用标准库函数而不是自己编写。 而且,正如它所发生的那样,有一个标准库函数可以在字符串中搜索字符并返回指向该字符的指针。 (它处理一个字符串,因此请查看具有前缀“str”的函数)(库函数几乎肯定会被优化以使用专门的 CPU 操作码来完成任务,而手写代码则不会)
设置指向字符串开头的临时指针(例如“ptr”)。
在循环中,使用 ptr 作为参数调用上面的函数,并将其设置为返回值。
增加计数器。
当未找到“e”时,将指针处的字符设置为“3”。
In general, it's better use a standard library function rather than rolling your own. And, as it just so happens, there is a standard library function that searches a string for a character and returns a pointer to it. (It deals with a string, so look among the functions that have the prefix "str") (The library function will almost certainly be optimized to use specialized CPU opcodes for the task, that hand written code would not)
Set a temp pointer (say "ptr") to the start of the string.
In a loop, call the function above using ptr as the parameter, and setting it to the return value.
Increment a counter.
Set the character at the pointer to "3" break when 'e' is not found.
你们中的一些人是从中间开始的。
更好的开始是
Some of you guys are starting in the middle.
A better start would be