2011-02-19 60 views
8

我想切掉字符數組中的最後4個字符,我嘗試了python使用沒有成功的方法;在c + +中的數組切片

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

cout << chartwo << endl; 

我想要這段代碼返回;

four 

但C/C++似乎不那麼容易......

我在哪裏能找到一個簡單的替代方案,將在最後4個字符一個字符數組的返回到另一個字符數組?

+0

你爲什麼投?是因爲你使用的是gcc,它會給出警告? – 2011-02-19 02:16:43

+0

是的XP,當我沒有,我通常會得到一個分段錯誤。 – MetaDark 2011-02-19 02:23:05

+1

對,在C++中,字符串文字是const char,所以你應該使用一個const char *來指向它。這也許是編譯器告訴你的。 – 2011-02-19 10:51:16

回答

12

嘗試:

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

在C++中,你可以用替換:

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

的代碼使用C字符串的特殊屬性,僅適用於斬去一個字符串的開頭。

1

這將做到這一點:

char* chartwo = charone + 16; 
7

首先,讓我們刪除過時的轉換:

char const *charone = "I need the last four"; 

數組是不是在C++一流的價值,他們不支持片斷。但是,正如上面的charone指向數組中的第一個項目,您可以指向任何其他項目。指針與chars一起使用來創建C風格的字符串:指向字符的字符,直到空字符爲字符串的內容爲止。因爲你想要的字符是在當前(charone)字符串的結尾,你可以在「F」指出:

char const *chartwo = charone + 16; 

或者,處理任意字符串值:

char const *charone = "from this arbitrary string value, I need the last four"; 
int charone_len = strlen(charone); 
assert(charone_len >= 4); // Or other error-checking. 
char const *chartwo = charone + charone_len - 4; 

或者,因爲您使用C++:

std::string one = "from this arbitrary string value, I need the last four"; 
assert(one.size() >= 4); // Or other error-checking, since one.size() - 4 
// might underflow (size_type is unsigned). 
std::string two = one.substr(one.size() - 4); 

// To mimic Python's [-4:] meaning "up to the last four": 
std::string three = one.substr(one.size() < 4 ? 0 : one.size() - 4); 
// E.g. if one == "ab", then three == "ab". 

尤其注意的std :: string給你不同值,所以無論是修改字符串不修改其他如發生s用指針。

3

如果你正在尋找只是短暫訪問的最後四個字符,然後像

char* chartwo = charone + (strlen(charone) - 4); 

將被罰款(加上一些錯誤檢查)。

但是,如果你要複製的蟒蛇功能,則需要副本最後四個字符。再次,使用strlen獲取長度(或將其存儲在某個地方),然後使用strcpy(或者可能是一個更好的具有相同功能的stl函數)。像...

char chartwo[5]; 
strcpy(chartwo, charone + strlen(charone) - 4); 

(注:如果你不復制,那麼你就不能免費charone直到您使用完chartwo。另外,如果你不復制,那麼如果你稍後改變charone,那麼chartwo也會改變。如果沒關係,那麼肯定只是指向偏移量。)

1

陣列在C++切片:

array<char, 13> msg = {"Hello world!"}; 
array<char, 6> part = {"world"}; 

// this line generates no instructions and does not copy data 
// It just tells the compiler how to interpret the bits 
array<char, 5>& myslice = *reinterpret_cast<array<char,5>*>(&msg[6]); 

// now they are the same length and we can compare them 
if(myslice == part) 
    cout<< "huzzah"; 

這僅僅是其中的切片是有用的emamples之一

我已經作出了小庫,執行此編譯時在https://github.com/Erikvv/array-slicing-cpp

邊界檢查