C++String.h字符表截断不带strstr的单词

C++ String.h Char Tables cutting-off word without strstr

本文关键字:strstr 单词 字符 C++String      更新时间:2023-10-16

我需要C++<string.h>字符表的帮助。。。。如何在没有strstr的情况下使用"*"运算符从句子中剪切单词?例如:"StackOverFlow是在线网站"。我必须切断"StackOverFlow",并使用运算符将其留在表中"是在线网站",没有strstr。我哪儿也找不到。

主要喜欢:

char t[]
int main
{
strcpy(t,"Stackoverflow is online website");
??? 
(Setting first char to NULL, then strcat/strcpy rest of sentence into table)
}

抱歉英语有问题/命名不正确。。。我开始学习C++

您可以这样做。请更好地解释你需要什么。

char szFirstStr[] = "StackOverflow, flowers and vine.";
strcpy(szFirstStr, szFirstStr + 15);
std::cout << szFirstStr << std::endl;

将输出"花和藤"。

对于c++程序员来说,使用c字符串不是一种好的风格,请使用std::string类。

您的代码显然在语法上不正确,但我想您已经意识到了这一点。

变量t实际上是一个char数组,并且有一个指向该char数组的第一个字符的指针,就像有一个指针指向以null结尾的字符串的第一个字符串一样。您可以做的是将指针值更改为指向字符串的新起点。

你可以这样做,或者如果你确实使用了一个数组,你可以从你想要使用的新起点的指针复制。因此,如果您希望复制的数据位于指向的内存中

const char* str = "Stackoverflow is an online website";

这在内存中看起来如下:

Stackoverflow is an online website
str points to:      --^

如果你想指向不同的起点,你可以改变指针指向不同的起始位置:

Stackoverflow is an online website
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++字符串处理的讲座,因为我认为这与学习指针有关。但很明显,这是对字符串的非常低级的修改。

作为一个初学者,为什么要让它变得更难呢?

使用std::string

substr()链接