是C ++字符串类的指针算术吗? [英] Is pointer arithmetic possible with C++ string class?

查看:139
本文介绍了是C ++字符串类的指针算术吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中编程了一点后,我决定跳进C ++。起初,我很高兴看到字符串类的存在,并能够将字符串作为整数而不是字符数组。但我很快发现,C风格的字符串有让程序通过字符移动,使用指针算术,并执行所需的逻辑操作的优势。

After programming a little in C I decided to jump right into C++. At first I was pleased with the presence of the string class and being able to treat strings as whole units instead of arrays of characters. But I soon found that the C-style strings had the advantage of letting the program move through it character by character, using pointer arithmetic, and carry out a desired logical operation.

我现在发现自己在需要这种情况,但编译器告诉我,它无法从类型字符串转换为C风格的字符串。所以我想知道,有没有办法使用指针算术来引用单个字符或传递参数到一个函数作为第一个字符的地址,而仍然使用字符串类,而不必创建字符数组或我只想要有我的蛋糕,也吃了吗?

I have now found myself in a situation that requires this but the compiler tells me it is unable to convert from type string to the C-style strings. So I was wondering, is there a way to use pointer arithmetic to reference single characters or to pass arguments to a function as the address of the first character while still using the string class without having to create arrays of characters or do I just want to have my cake and eat it too?

推荐答案

字符串字符可以通过索引,指针和通过使用迭代器访问。

string characters can be accessed by index, pointers, and through the use of iterators.

如果您想使用迭代器,可以使用一个函数来检查字符串中是否有空格:

if you wanted to use iterators, you could make a function that checks whether a string has a space in it or not:

bool spacecheck(const string& s)
{
    string::const_iterator iter = s.begin();
    while(iter != s.end()){
        if (isspace(*iter))
            return true;
        else
            ++iter;
    }
}

在函数的开头,我初始化了一个迭代器到 s 的开头,使用 .begin()函数,在这种情况下,它会向字符串中的第一个字符返回一个迭代器。在while函数中,条件是 iter != s.end()。在这种情况下, end()在迭代器中返回字符串最后一个字符后的元素。在正文中,由iter指向的值(* iter)被发送到函数 isspace(),该函数检查字符是否为空格。如果失败,迭代将增加,这使得iter指向字符串的下一个元素。

At the beginning of the function, I initialized an iterator to the beginning of the string s by using the .begin() function, which in this case returns an iterator to the first character in a string. In the while function, the condition is that iter != s.end(). In this case end() returns in iterator referring to the element after the last character of the string. In the body, (*iter), which is the value pointed to by iter, is sent to the function isspace(), which checks if a character is a space. If it fails, iter is incremented, which makes iter point to the next element of the string.

我自己学习c ++,通过写所有这些东西帮助我自己了解一些。我希望我没有冒犯你,如果这一切看起来很简单,我只是想简洁。

I am learning c++ myself and by writing all of this stuff out it has helped my own understanding some. I hope I did not offend you if this all seemed very simple to you, I was just trying to be concise.

我目前正在学习加速c + +,我不能推荐它足够高!

I am currently learning from Accelerated c++ and I could not recommend it highly enough!

这篇关于是C ++字符串类的指针算术吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆