2014-09-23 749 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

相關問題