在2D字符串数组中查找字符串数
find the number of strings in 2D array of strings
给定一个字符串数组,我需要找出其中的字符串数。
我跟踪了这个
但是如果我把它传递到一个函数中,这是不起作用的。
这是我试过的代码
#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int f1(char* input1[])
{
string s="";
cout<<sizeof(input1)<<endl; //print 4
cout<<sizeof(char*)<<endl; //print 4
int l=sizeof(input1) / sizeof(char*);
//giving l=1 here but should be 8
}
int main()
{
char *str2[]={"baba","sf","dfvf","fbfebgergrg","afvdfvfv","we","kkhhff","L"};
int l=sizeof(str2) / sizeof(char*);
cout<<l<<endl; //print 8
cout<<sizeof(str2)<<endl; //print 32
cout<<sizeof(char*)<<endl; //print 4
f1(str2);
}
sizeof(char*)
为您提供char*
指针的大小(在您的系统中为4)。
sizeof(str2)
将为您提供数组str2
的大小。共有8个元素,每个元素都是一个指针类型。因此,系统的总大小为8 x 4=32。
要获取字符串的长度,请使用strlen
。
请考虑将std::vector<std::string>>
作为C++中的替代方案。
如果你只有一个指向数组的指针,你就无法知道数组的长度。而且你只有指针,因为你无法按值传递数组。传递给函数的数组将自动衰减为指针,参数类型char* foo[]
等效于char** foo
。size_of
没有帮助,因为它只会告诉指针本身的大小。
将长度作为参数传递给f1
。或者更好的是,使用std::vector
或std::array
。
我无法修改给定的功能原型
很不幸。那你就得耍花招了。最简单的解决方法是将长度存储在全局变量中,而不是函数参数中。
另一种可能是终止值。例如,始终以nullptr结束数组,并且从不允许其他元素具有该值。与c字符串以null字符终止的方式相同。然后,当遇到nullptr时,可以停止迭代数组。但我认为您也不能修改数组。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分