将c ++字符串视为指针

时间:2016-02-21 05:07:45

标签: c++ string pointers

免责声明 - 我来自严格的C背景。

如何使用STL和std::string而不是char*来跳过像这样的字符串(公认的荒谬)示例?

const char* s = "XXXXXXXXhello";
while (*s == 'X') 
    s++;

s += 2;
std::cout << --(--s); //prints `hello`

3 个答案:

答案 0 :(得分:3)

如果您想要做的是修改对象,并摆脱“ h ”:

$res = SQL_Query_exec("SELECT * FROM 'users' WHERE 'passkey' =".sqlesc($passkey)) or err("Cannot Get User Details");
$row = mysql_fetch_assoc($res);
$memid = $row["id"];
$memclass = $row["class"];

//check if Torrent is a VIP Torrent
$res = SQL_Query_exec("SELECT * FROM torrents WHERE info_hash=".sqlesc($info_hash)) or err("Cannot Get Torrent Details");; 
$row = mysql_fetch_assoc($res);
if ($row["category"]>=204 && $row["category"]<=218){ // Category 204 to 218 are all VIP Categories
goto tezt;//yes VIP
}
else{
goto enz;//no NON VIP
}
//is this Torrent Seeding only
tezt:
$query = ("SELECT 'seeder' FROM 'peers' WHERE ('userid' = $memid) AND 'torrent' = $torrentid") or err("Contact Admin");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
goto enz; // Torrent is seeding - even if user not VIP - okay to seed
}
// Torrent is downloading - do a VIP USER check
if ($memclass<=2){
      err("User can't download VIP Content");
}
enz:

std::string s = "hello";
s = s.substr(1); // position = 1, length = everything (npos)
std::cout << s;  //"ello"

答案 1 :(得分:0)

perfer @José的第二个答案,无需修改原始的str

只是std::cout<<s.substr(1)<<endl

编辑过的问题:

std::string s = "hello world!";
cout<<s.substr(s.find_first_of('e'))<<endl; // == "ello world!"

man std :: string:

http://www.cplusplus.com/reference/string/string/?kw=string

答案 2 :(得分:0)

如果你想在不修改字符串的情况下跳转,你可以使用索引或迭代器:

std::string const s("XXXXXXXXhello");

int idx = 0;
while ( s[idx] == 'X' ) 
    ++idx;

idx += 2;
std::cout << &s[idx -= 2] << '\n';

迭代器版本:

auto it = s.begin();
while (*it == 'X')
    ++it;

it += 2;
std::cout << &*it << '\n';

从C ++ 11开始,保证std::string与null终止符一起存储,因此您可以使用&输出字符串的尾部。在旧的代码库中,您需要从s.c_str()编制索引。