数组切片在c ++ [英] Array slicing in c++

查看:189
本文介绍了数组切片在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

我试图将字符数组的最后4个字符切分, > char * charone =(char *)(I need the last four)
char * chartwo = charone [-4:]

cout<另外, endl

我想让这段代码返回;

  four 

但是c / c ++似乎



在哪里可以找到一个简单的替代方法,将一个char数组的最后4个字符返回到另一个char数组?

解决方案

尝试:

  int len = strlen charone); 
char * chartwo = charone +(len <4?0:len - 4);

在C ++中,您可以用以下代替:

  char * chartwo = charone +(std :: max)(strlen(charone),4) 

代码使用C字符串的特殊属性,只适用于截断字符串的开头。


I am trying to slice the last 4 characters off a character array and I tried the method that python uses without success;

char *charone = (char*)("I need the last four")
char *chartwo = charone[-4:]

cout << chartwo << endl;

I would want this code to return;

four

but c/c++ doesn't seem to be that easy...

Where could I find a simple alternative that will return the last 4 chars of one char array into another char array?

解决方案

Try:

int len = strlen(charone);
char *chartwo = charone + (len < 4 ? 0 : len - 4);

In C++, you can replace that with:

char* chartwo = charone + (std::max)(strlen(charone), 4) - 4;

The code uses a special property of C strings that only works for chopping off the beginning of a string.

这篇关于数组切片在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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