您的代码显然在语法上不正确,但我想您知道这一点。
您的变量t
实际上是一个 char 数组,并且您有一个指向该 char 数组的第一个字符的指针,就像您有一个指向空终止字符串的第一个字符的指针一样。您可以做的是更改指针值以指向字符串的新起点。
您可以这样做,或者如果您确实使用数组,您可以从您希望使用的新起点的指针复制。因此,如果您要复制的数据驻留在指向的内存中:
const char* str = "Stackoverflow is an online website";
这在内存中如下所示:
Stackoverflow is an online website\0
str points to: --^
如果要指向不同的起点,可以将指针更改为指向不同的起点:
Stackoverflow is an online website\0
str + 14 points to: --------------^
您可以将“i”的地址传递给您的strcpy
,如下所示:
strcpy(t, str + 14);
显然,如果不进行分析(14),您不确定要截断的大小,您可能会在字符串中搜索空格后面的第一个字符。
// Notice that this is just a sample of a search that could be made
// much more elegant, but I will leave that to you.
const char* FindSecondWord(const char* strToSearch) {
// Loop until the end of the string is reached or the first
// white space character
while (*strToSearch && !isspace(*strToSearch)) strToSearch++;
// Loop until the end of the string is reached or the first
// non white space character is found (our new starting point)
while (*strToSearch && isspace(*strToSearch)) strToSearch++;
return strToSearch;
}
strcpy(t, FindSecondWord("Stackoverflow is an online website"));
cout << t << endl;
这将输出:是一个在线网站
由于这很可能是一项学校作业,因此我将跳过有关更现代的 C++ 字符串处理的讲座,因为我希望这与学习指针有关。但显然这是对字符串的非常低级的修改。