修剪一串 Int
在我的程序中,我想输入一个整数字符串,例如 2107900000。我想获取它的长度,然后删除所有 0 和 1。
In my program i want to input a string of integer e.g 2107900000. I want to get its length and then want to remove all the 0's and 1's.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您想要构造一个新字符串,并且我假设您想要一个仅接受指向此类字符串的指针的函数:(其中假设
stripped
指向的内容至少是相同的大小与orig
所指向的一样)我相信使用两个参数的相同指针调用它应该就地进行替换...
要解决有关在运行时查找输入字符串长度的问题,您可以做类似的事情:(
编辑:更改为删除使用
new
作为变量名)(编辑:添加有关运行时输入字符串和查找字符串长度的信息)
Supposing you want to construct a new string, and I'll assume that you want a function that simply accepts a pointer to such a string: (where it's assumed what's pointed at by
stripped
is at least the same size as what's pointed at byorig
)I believe calling this with the same pointer for both arguments should do the replacements in-place...
To address your question about finding length of input strings at runtime you can do something like:
(edit: changed to remove use of
new
as a variable name)(edit: added info about input strings at runtime and finding string length)
也许不是最佳选择,但您可以有条件地将其复制到另一个缓冲区中:
或者您可以在单个缓冲区中执行此操作:
Perhaps not optimal, but you could copy it into another buffer conditionally:
Or you could do it in a single buffer:
for (i=j=0; s[i]=s[j]; i+=((unsigned)s[j++]-'0'>2));
好的,因为有需求解释一下,其想法是迭代具有 2 个索引的字符串:目标 (
i
) 和源 (j
)。在每一步中,都会从源索引复制一个字符到目标索引,由于复制是循环条件,因此如果复制的字符为空终止符,则循环将终止。在每次迭代中,源索引都会递增 (j++
),但目标索引仅在复制的字符不是 0 或 1 时才会递增(如果它是这两个字符之一,则目标索引将递增)。只需在下一次迭代时被覆盖)。测试(unsigned)s[j++]-'0'>2
使用模算术和数字 0-9 具有连续值作为字符的属性来执行源是否为最佳测试字符超出'0'
到'1'
范围,并且该真值(对于 false 或 true 分别计算为 0 或 1)用作金额增加目标索引。for (i=j=0; s[i]=s[j]; i+=((unsigned)s[j++]-'0'>2));
OK since there's demand for an explanation, the idea is to iterate through the string with 2 indices, a destination (
i
) and source (j
). At each step, a character is copied from the source index to the destination index, and since the copy is the loop condition, it will terminate if the character copied is the null terminator. At each iteration, the source index gets incremented (j++
), but the destination index is only incremented if the character copied was not a 0 or a 1 (if it was one of these two characters, it will simply get overwritten on the next iteration). The test(unsigned)s[j++]-'0'>2
uses modular arithmetic and the property that the digits 0-9 have consecutive values as characters to perform an optimal test as to whether the source character is outside the range'0'
to'1'
, and this truth value (which evaluates to 0 or 1 for false or true, respectively) gets used as the amount to increment the destination index by.