0

我需要有关 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++

4

3 回答 3

1

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

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

将输出“花与藤”。

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

于 2016-06-09T10:26:33.877 回答
0

您的代码显然在语法上不正确,但我想您知道这一点。

您的变量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++ 字符串处理的讲座,因为我希望这与学习指针有关。但显然这是对字符串的非常低级的修改。

于 2016-06-09T10:27:09.150 回答
0

作为一个初学者,为什么要让它变得更难,那么它真的必须是?

使用 std::string

substr() 链接

于 2016-06-09T10:59:46.377 回答