字符串操作
有没有一种正确的方法可以在某个点之后复制字符串的一部分。
Party City 1422 Evergreen Street
我使用 strpbrk() 来复制名称,我总是可以通过空格对其进行标记,但是是否有一种字符串过程或技术可以让我除了从头开始复制字符串的特定部分之外,就像复制 [1422 Evergreen Street ] 或删除字符串的第一部分?
Is there a proper way to just copy a part of a string after a certain point.
Party City 1422 Evergreen Street
I use strpbrk() to copy the name out, I could always just tokenize it by white space but is there a string process or technique where I can copy out a specific section of a string besides from the beginning like copy just [1422 Evergreen Street] or delete the first portion of the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你想通过起始位置和长度来指定它,你总是可以使用 strncpy 和一些指针算术。
编辑:当您知道可以使用的起始字符串时
If you want to specify it by starting position and length, you can always use strncpy and a bit of pointer arithmetic.
EDIT: When you know the starting string you can use
如果您知道要选择的子字符串的第一个和最后一个字符的索引,则应该使用 strncpy。请参阅以下代码片段,从给定 startIndex 处的 inputStr 字符串复制 substringLength 字符。
If you know the first and last characters' indexes of the substring you want to pick, you should do this with strncpy. See the following snippet to copy substringLength characters from the inputStr string at the given startIndex.
如果您想在特定字符串的位置进行拆分,您可以执行以下操作:
哪个输出:
If you want to split at the location of a particular string, you can do something like this:
Which outputs:
实际上,对于当前的任务来说,strncpy 并不是一个特别好的选择。它总是将你的值填充到占据整个目的地,这通常是相当浪费的(它最初是为了将文件名放入 Unix 文件系统而设计的;这对此很有好处,但除此之外就没有什么用了)。
我想我会使用 sscanf。假设我们总是想从第一个数字复制到字符串的末尾,你可以这样做:
FWIW,
%*[^0-9]
部分会跳过字符,直到到达某个位置在 0-9 范围内(是的,我知道它看起来像正则表达式,但 scanf 和公司也支持它)。其中的*
表示扫描但不分配它找到的内容。%255[^\n]
表示读取并分配,直到输入中的下一个换行符,或最多 255 个字符,以先到者为准。Actually,
strncpy
is not a particularly good choice for the task at hand. It always pads your value out to occupy the entire destination, which is generally pretty wasteful (it was originally designed for putting file names into the Unix file system; it's good for that, but not really much else).I think I'd use
sscanf
. Assuming we always want to copy from the first digit to the end of the string, you could do something like this:FWIW, the
%*[^0-9]
part skips over characters until it reaches something in the range 0-9 (yes, I know it looks like a regex, but scanf and company support it too). The*
in it means to scan but not assign what it finds. The%255[^\n]
means to read and assign until the next newline in the input, or up to 255 characters, whichever comes first.在一般情况下可能是不可能的,您最好在单独的字段中获取输入,但如果这不是一个选项,则以下操作应该有效:
根据需要进行修改和错误检查。
Probably impossible in the general case, and you would do better to get the input in seperate fields, but if thats not a option, something the following should work:
modify and error-check as needed.