【问题标题】:C++ String.h Char Tables cutting-off word without strstrC++ String.h Char Tables 不带strstr的截字
【发布时间】:2016-06-09 10:19:16
【问题描述】:

我需要 C++ <string.h> char 表方面的帮助...。如何使用“*”运算符从句子中截取单词,而不使用 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++

【问题讨论】:

  • 我理解你的意思吗?您需要切断 c 字符串的一部分并将其存储在同一个变量中吗?在这种情况下,有什么反对 strstr 的理由吗?你总是可以自己实现它,但这就像自行车改造

标签: c++ char operators string.h


【解决方案1】:

你可以做这样的事情。请更好地解释您的需求。

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

会输出“花与藤”。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      使用 std::string

      substr() Link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 2014-05-12
        • 1970-01-01
        • 1970-01-01
        • 2021-03-25
        相关资源
        最近更新 更多