从索引 1 到字符串末尾的子字符串
Substring from index 1 until the end of string
假设我有
char* string = "1234567";
获取字符串 "234567"
的最简单方法是什么?
您可以设置一个指向第二个字符的指针,类似于以下之一:
char *fromSecondChar = string + 1;
char *fromSecondChar = &(string[1]);
请注意,这不会对空字符串执行您想要的操作,您可能应该先检查一下:
char *fromSecondChar = string;
if (*string != '[=11=]') fromSecondChar++;
另请记住,这是指向字符串文字本身的指针,因此适用正常的修改规则(不要尝试这样做)。如果你想要一个可以修改的 separate staring,你需要 strcpy
它到其他地方。
或者你可以从第二个字符 strdup
如果你对动态分配的缓冲区感到满意并且你的实现实际上 有 一个 strdup
(它是ISO C 标准未强制要求)。这可以通过类似的方式完成:
char *fromSecondChar = strdup (string + 1);
if (fromSecondChar == NULL)
doSomethingIntelligent();
:
free (fromSecondChar); // at some point.
如果你想让子串在一个单独的内存中,那么你可以像下面那样做。
char new_string[max_size];
strcpy(new_string, old_string + 1);
假设我有
char* string = "1234567";
获取字符串 "234567"
的最简单方法是什么?
您可以设置一个指向第二个字符的指针,类似于以下之一:
char *fromSecondChar = string + 1;
char *fromSecondChar = &(string[1]);
请注意,这不会对空字符串执行您想要的操作,您可能应该先检查一下:
char *fromSecondChar = string;
if (*string != '[=11=]') fromSecondChar++;
另请记住,这是指向字符串文字本身的指针,因此适用正常的修改规则(不要尝试这样做)。如果你想要一个可以修改的 separate staring,你需要 strcpy
它到其他地方。
或者你可以从第二个字符 strdup
如果你对动态分配的缓冲区感到满意并且你的实现实际上 有 一个 strdup
(它是ISO C 标准未强制要求)。这可以通过类似的方式完成:
char *fromSecondChar = strdup (string + 1);
if (fromSecondChar == NULL)
doSomethingIntelligent();
:
free (fromSecondChar); // at some point.
如果你想让子串在一个单独的内存中,那么你可以像下面那样做。
char new_string[max_size];
strcpy(new_string, old_string + 1);