我有char * source,我想从中提取subsrting,我知道从符号“abc”开始,并在源结束处结束。与strstr我可以得到poiner,但不是位置,没有位置,我不知道子字符串的长度。我怎样才能得到纯C的子字符串的索引?获取子字符串的索引
回答
如果你有指向字符串的第一个字符,和子在源字符串的结尾结束,则:
strlen(substring)
会给你它的长度。substring - source
会给你开始索引。
谢谢大家!我不能投票,因此我只能说谢谢 – Country
char *source = "XXXXabcYYYY";
char *dest = strstr(source, "abc");
int pos;
pos = dest - source;
oops'source =“abracadabcabcabcabc”':) – pmg
@pmg - 无所谓 - “以'abc'开头”仍然创建正确的结果作为strstr ()停止查找,一旦它成功 – KevinDTimm
我想用malloc分配一个数组只是为了使示例更完整。当然,我也会做一些错误检查;-) –
形式上,其它的是正确的 - substring - source
确实开始索引。但是你不需要它:你可以使用它作为source
的索引。因此,编译器计算source + (substring - source)
作为新地址 - 但只有substring
对于几乎所有用例都足够了。
只是提示优化和简化。
谢谢大家!我不能投票的原因,所以我只能说,谢谢你 – Country
的开始和结束字
string search_string = "check_this_test"; // The string you want to get the substring
string from_string = "check"; // The word/string you want to start
string to_string = "test"; // The word/string you want to stop
string result = search_string; // Sets the result to the search_string (if from and to word not in search_string)
int from_match = search_string.IndexOf(from_string) + from_string.Length; // Get position of start word
int to_match = search_string.IndexOf(to_string); // Get position of stop word
if (from_match > -1 && to_match > -1) // Check if start and stop word in search_string
{
result = search_string.Substring(from_match, to_match - from_match); // Cuts the word between out of the serach_string
}
问题是关于C,而不是C++ –
在C + +有更简单的方法来做到这一点 - 使用字符串::查找方法和字符串构造函数字符串(常量字符串&str ,size_t pos,size_t n = npos); – Alecs
这里切一个字一个字符串的函数是有偏移的特征对strpos函数的C版...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
char *p = "Hello there all y'al, hope that you are all well";
int pos = strpos(p, "all", 0);
printf("First all at : %d\n", pos);
pos = strpos(p, "all", 10);
printf("Second all at : %d\n", pos);
}
int strpos(char *hay, char *needle, int offset)
{
char haystack[strlen(hay)];
strncpy(haystack, hay+offset, strlen(hay)-offset);
char *p = strstr(haystack, needle);
if (p)
return p - haystack+offset;
return -1;
}
- 1. 获取字符串索引
- 2. 通过搜索字符串获取子字符串文本来获取字符串的子字符串?
- 3. 获取字符串中最后一个子串索引后的字符
- 4. 子索引成字符串
- 5. 获取字符从字符串列表索引到的字符
- 6. 基于xsl/xslt中的特定索引获取子字符串
- 7. 获取第一个包含子字符串的索引?
- 8. hw搜索索引字符串列表中的子字符串?
- 9. 从字符串获取子字符串__
- 10. 获取字符索引
- 11. 获取solaris上子串的索引
- 12. 获取查询命中索引 - 搜索字符串的前缀
- 13. Python:如何从没有索引的字符串中获取子串?
- 14. KDB获取子字符串
- 15. 查找字符串中子字符串的所有索引
- 16. Noob,创建字符串方法的索引和子字符串
- 17. 获取子串给定的字符串
- 18. Python:索引字符串中的子索引的位置
- 19. 字符串索引
- 20. 在给定索引处从NSString中提取字子字符串
- 21. SQL子字符串和最后索引
- 22. 如何获得PHP子字符串的索引0
- 23. 字符串索引必须是整数 - 子字符串
- 24. 获取匹配的阵列中的字符串作为索引
- 25. PHP从字符串获取子串
- 26. 从字符串获取子串C
- 27. Python:如何获取字符串的索引
- 28. 获取一个redis列表中特定字符串的索引?
- 29. 通过索引获取字符串的特定部分?
- 30. 如何获取字符串值的最后一个索引
你可以用指针来做你想要的,而不用担心长度。 – pmg
@Country - 没有理由不投票(这可能会限制频率) – KevinDTimm