【问题标题】:last index of C-style string in C++ [closed]C++中C风格字符串的最后一个索引[关闭]
【发布时间】:2013-10-12 23:23:34
【问题描述】:

我尝试为我的 C++ 类编写 lastindexOf 函数。在我尝试了 2 周后,我仍然无法让它工作。 起初,我试图遵循这篇文章中的逻辑:CString find the last entry,但由于他们使用 CString 类而不是 char 类,我没有成功复制 char 类的代码。我也尝试了 strstr,但我也没有运气。我将不胜感激。
这是我到目前为止提出的代码:

#包括

using namespace std;
int lastIndexOf(char *s, char target);
int main()
{
 char input[50];
 cin.getline(input, 50);
 char h = h;
 lastIndexOf(input, h);
 return 0; 
 }
 int lastIndexOf( char *s, char target)
 {   
int result = -1;

while (*s != '\0')
{
  if (*s == target ){
   return *s; 
 }}
 return result;
 }

【问题讨论】:

  • 您正在寻找strchr()。顺便说一句,您的错误是您没有增加 while 循环的循环计数器,因此它将是无限的。
  • 对于 lastIndexOf(),strrchr() 可能会更好。

标签: c++ arrays c-strings


【解决方案1】:

试试这个:

int lastIndexOf(const char * s, char target)
{
   int ret = -1;
   int curIdx = 0;
   while(s[curIdx] != '\0')
   {
      if (s[curIdx] == target) ret = curIdx;
      curIdx++;
   }
   return ret;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2011-08-06
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多