C++String.h字符表截断不带strstr的单词
C++ String.h Char Tables cutting-off word without strstr
我需要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()链接
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 当您在此单词中搜索单词时调整字符数组的大小?
- 数每个单词的元音
- 我们如何在文本文件中找到C++中的几个单词?
- 使用 BFS 的单词梯 2
- C++String.h字符表截断不带strstr的单词