问题描述
char string[] = "var1+vari2+varia3";
for (int i = 0; i != sizeof(string); i++) {
memcpy(buf,string[0],4);
buf[9] = '\0';
}
因为变量的大小不同,所以我试图写一些东西,将字符串带入循环并提取(除)变量。有什么建议 ?我期望的结果如下:
var1
vari2
varia3
解决方法
您可以使用strtok()
通过定界符来分隔字符串
char string[]="var1+vari2+varia3";
const char delim[] = "+";
char *token;
/* get the first token */
token = strtok(string,delim);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n",token );
token = strtok(NULL,delim);
}
有关strtok()
的更多信息,请访问:https://man7.org/linux/man-pages/man3/strtok.3.html
您可以使用一个简单的循环来扫描字符串中的+
符号:
char string[] = "var1+vari2+varia3";
char buf[sizeof(string)];
int start = 0;
for (int i = 0;;) {
if (string[i] == '+' || string[i] == '\0') {
memcpy(buf,string + start,i - start);
buf[i - start] = '\0';
// buf contains the substring,use it as a C string
printf("%s\n",buf);
if (string[i] == '\0')
break;
start = ++i;
} else {
i++;
}
}
,
在我看来,您不仅希望打印单个字符串,而且希望将单个字符串保存在某个缓冲区中。
由于您既不知道字符串的数量也不知道单个字符串的长度,因此应该动态分配内存,即使用realloc,calloc and malloc
之类的函数。
它可以通过多种方式实现。以下是一个示例。为了使示例简单,无论如何都没有对性能进行优化。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char** split_string(const char* string,const char* token,int* num)
{
assert(string != NULL);
assert(token != NULL);
assert(num != NULL);
assert(strlen(token) != 0);
char** data = NULL;
int num_strings = 0;
while(*string)
{
// Allocate memory for one more string pointer
char** ptemp = realloc(data,(num_strings + 1) * sizeof *data);
if (ptemp == NULL) exit(1);
data = ptemp;
// Look for token
char* tmp = strstr(string,token);
if (tmp == NULL)
{
// Last string
// Allocate memory for one more string and copy it
int len = strlen(string);
data[num_strings] = calloc(len + 1,1);
if (data[num_strings] == NULL) exit(1);
memcpy(data[num_strings],string,len);
++num_strings;
break;
}
// Allocate memory for one more string and copy it
int len = tmp - string;
data[num_strings] = calloc(len + 1,1);
if (data[num_strings] == NULL) exit(1);
memcpy(data[num_strings],len);
// Prepare to search for next string
++num_strings;
string = tmp + strlen(token);
}
*num = num_strings;
return data;
}
int main()
{
char string[]="var1+vari2+varia3";
// Split the string into dynamic allocated memory
int num_strings;
char** data = split_string(string,"+",&num_strings);
// Now data can be used as an array-of-strings
// Example: Print the strings
printf("Found %d strings:\n",num_strings);
for(int i = 0; i < num_strings; ++i) printf("%s\n",data[i]);
// Free the memory
for(int i = 0; i < num_strings; ++i) free(data[i]);
free(data);
}
输出
Found 3 strings:
var1
vari2
varia3
,
您的代码没有任何意义。
我为您编写了这样的函数。有时以一些代码为基础进行分析
char *substr(const char *str,char *buff,const size_t start,const size_t len)
{
size_t srcLen;
char *result = buff;
if(str && buff)
{
if(*str)
{
srcLen = strlen(str);
if(srcLen < start + len)
{
if(start < srcLen) strcpy(buff,str + start);
else buff[0] = 0;
}
else
{
memcpy(buff,str + start,len);
buff[len] = 0;
}
}
else
{
buff[0] = 0;
}
}
return result;
}