我有
char t[200];
cin.get(s, 200);
int i = 5;
int j = 10;
除了将每个元素单独复制到另一个数组之外,是否有任何简单的方法可以从substriing(i,j)
获取t
?没有strings
等等char t[200]
。
答案 0 :(得分:6)
如果您允许修改t
,则可以将t[j]
设置为0
,然后使用t + i
获取子字符串。
如果没有,你将不得不复制。
那就是说,为什么你不能只使用std::string
并为自己省去头痛?
答案 1 :(得分:2)
如果你只需要读取数据,那么t + i就是你想要的,唉你必须管理子串的长度......
char *sub = t+i;
int len = j-i;
printf("%.*s\n",len,sub);
如果您需要具有子字符串的不同副本,则必须复制。
答案 2 :(得分: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];
答案 3 :(得分: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;
答案 4 :(得分: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;
答案 5 :(得分: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;
}