2014-09-23 758 views
0

基本上我试图在char *数组中找到最后一个字符。 例如;我有这个字符串:C++查找char数组中的最后一个字符

"This is a long string with many other \"characters\". Hehehe" 

我试图用这样的:

int findLast (const char* buffer, int pos, char character, int size) 
{ 
    int last = 0; 

    for (int i = pos; i < size; i++) 
    { 
     if (buffer[i] == character) 
      last = i; 
     if (buffer[i] == '\n') 
      return last; 
    } 

    return last; 
} 

像这样:

int lastCharPos = findLast (charArray, ftell(file), '"', charSize); 

在charArray我们:

"This is a long string with many other \"characters\". Hehehe" 

findLastChar回报“之后”的位置cters“,但最后一个应该在Hehehe之后。

这个想法是返回由用户请求指定的最后一个“字符”的位置,但它不起作用。

我想这个字符串中使用它:

"Welcome to Stackoverflow!\nWe seriously hope you have a \"great\" time." 

它返回(代码表示,“后大是最后一个,但你可以在给定的字符串中所看到的,它不是) :

"Welcome to Stackoverflow!\nWe seriously hope you have a \"great\" 

试图用它来搜索“

+3

你是什么意思,它返回''欢迎来到Stackoverflow!\ n我们真的希望你有一个\“伟大\”''?你正在返回一个'int',而不是'char *'或者'std :: string'。 – wolfPack88 2014-09-23 19:03:27

+1

你没有使用'std :: string'的任何特定原因? – Biffen 2014-09-23 19:03:35

+0

也许你没有正确地调用你的函数? – dasblinkenlight 2014-09-23 19:04:31

回答

1

这个被标记C++,所以不要使用char*

#include <string> 

int findLastPos(std::string s, char c) 
{ 
    return s.rfind(string(1,c)); 
} 
+0

事情是,如果我的“字符串/字符*”组成如下:**“usernamename” \ n \ n“other user \”no other \“,return user”**这就是为什么我的函数包含数组中的当前位置,所以它不会使我想要的主要过程过程复杂化给定基于位置的缓冲区)。 – 2014-09-23 19:27:27

+0

是的,它会。你似乎对如何处理字符串感到困惑。将该文本放在.txt文件中,将其读入std :: string并尝试。它会工作 – sp2danny 2014-09-23 19:33:32

+0

试过了,没有工作。 – 2014-09-23 19:36:42

相关问题