2013-03-23 72 views
5

子串字符的[]在C++中

char t[200]; 
    cin.get(s, 200); 
    int i = 5; 
    int j = 10; 

有沒有什麼簡單的方式來獲得tsubstriing(i,j)每個元素seperately複製到另一個陣列旁邊?沒有strings等只是char t[200]

+6

這太模糊。有什麼用?您可以簡單地將索引(start,end)傳遞給需要子字符串的函數以及't' ... – Synxis 2013-03-23 12:10:58

+2

問題是標準C「字符串」是空終止的。這意味着,如果你舉個例子從5到10的子字符串,你不僅必須有第5個字符的地址(容易完成),但你也必須在第10個字符之後放置一個空值。這將在原始數組上「跺腳」。所以,要做一個「正確」的工作,必須複製字符串。 (但是,如果數組的其餘部分是「丟棄」的,那麼你可以從原始緩衝區開始工作。)(當然還有一個範圍問題需要考慮 - 一個char數組(不是指針)「存在」只在聲明它的方法內)。 – 2013-03-23 12:28:18

回答

5

如果您允許修改t,您可以將t[j]設置爲0,然後使用t + i獲取子字符串。如果不是,你將不得不復制一份。

這就是說,爲什麼你不能只使用std::string併爲自己節省頭痛?

0

這並不做任何邊界檢查,以確保目標數組足夠

char newt[200]; 
// copy j-i chars from position t+i to newt array 
strncpy(newt, t + i, j-i); 
// now null terminate 
newt[j-i] = 0; 
2

大如果你只需要讀取數據,則T +我是你想要的,唉,你必須管理你的子串的長度...

char *sub = t+i; 
int len = j-i; 
printf("%.*s\n",len,sub); 

如果你需要有一個不同的子字符副本,那麼你必須複製。

2

這應該很好地工作:

#include <string.h> 
#include <stdlib.h> 
#include <iostream> 

using namespace std; 

int main() 
{ 
char t[200]; 
cin.get(t, 200); 
int i = 5; 
int j = 10; 
char *to = (char*) malloc(j-i+1); 
strncpy(to, t+i, j-i); 
to[j-i]='\0'; 
cout << to; 
} 

可以使用new代替malloc這樣的:

char* to = new char[j-i+1]; 
+1

當你有'new'時,爲什麼'malloc'? – deepmax 2013-03-23 13:14:22

1

使用兩個指針來表示字符串中的範圍。

char const * beg = t+i; 
char const * end = t+j+1;  
std::cout.write(beg, end-beg); 

或者你可以使用封裝這個想法的類。標準庫中提出了something like that。同時,你可以自己寫,或者你可以使用庫中的一個。例如,llvm::StringRef

llvm::StringRef sref(t+i, j+1-i); 
std:cout << sref; 
0
char* substr(char* arr, int begin, int len) 
{ 
    char* res = new char[len]; 
    for (int i = 0; i < len; i++) 
     res[i] = *(arr + begin + i); 
    res[len] = 0; 
    return res; 
} 
+1

除了已有的代碼之外,您還可以提供更多關於答案的詳細信息嗎? – 2014-04-04 16:32:14