简体   繁体   English

传递字符串作为参数

[英]Passing string as argument

//EDITED: follow up question: //编辑:跟进问题:

But making the function as isUnique(const char *s) and then calling function as isUnique(str.c_str()) does not allow me to modify my string str in the function 但是将函数设为isUnique(const char *s)然后将函数调用为isUnique(str.c_str())不允许我在函数中修改我的字符串str
// //

I am having problem with passing a string: 我遇到传递字符串的问题:

bool isUnique(char *s)
{
    int arr[256] = {0};
    while(*s)
    {
        arr[*s]++;
        if(arr[*s]>1)
        {
            cout<<"not unique";
            return false; 
        }
    }
}
int main()
{
    string str = "abcda";
    cout<<"1: True : unique, 2: False: Not Unique"<<endl<<isUnique(str);
}

ERROR:cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'bool isUnique(char*)' 错误:无法将参数'1'的'std :: string {aka std :: basic_string}'转换为'char *'为'bool isUnique(char *)'

Pass the argument as: 将参数传递为:

isUnique(str.c_str());

And make the parameter type of the function as const char* : 并将函数的参数类型设为const char*

bool isUnique(const char *s)

Because std::string::c_str() returns const char* . 因为std::string::c_str()返回const char*

Or even better, make the parameter const string& : 或者甚至更好,使参数const string&

bool isUnique(const std::string & s);

And pass as you do : isUnique(str) . 并且像你一样传递: isUnique(str) Inside the function you can use s[i] to access the characters in the string, where 0 <= i < s.size() . 在函数内部,您可以使用s[i]访问字符串中的字符,其中0 <= i < s.size()

Use 采用

isUnique(str.c_str())

and make sure isUnique takes a char const * argument. 并确保isUnique采用char const *参数。

You are not passing a string. 你没有传递一个字符串。 You are passing a char * and trying to create one from a string . 您正在传递char *并尝试从string创建一个。 Of course the conversion from string to char * is not automatic - they are two very different things. 当然,从stringchar *的转换不是自动的 - 它们是两个非常不同的东西。

I suggest that you write this function: 我建议你写这个函数:

bool isUnique(const std::string& s)

Either change function to accept 要么改变功能要接受

bool isUnique(const string& s)

and pass the string as a const reference 并将该字符串作为const引用传递

or do as the two other fine people suggested. 或者像其他两个好人一样建议。

This being C++ it would be preferable to pass a const std::string& unless of course you have to be compatible with some C code or just have a requirement of using C-strings. 这是C ++,最好传递一个const std::string&除非你必须与某些C代码兼容,或者只需要使用C字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM