I have
char t[200];
cin.get(s, 200);
int i = 5;
int j = 10;
除了将每个元素单独复制到另一个数组中以外,是否有任何简单的方法从t
获取substriing(i,j)
?不使用strings
等,只使用char t [200]
。
I have
char t[200];
cin.get(s, 200);
int i = 5;
int j = 10;
除了将每个元素单独复制到另一个数组中以外,是否有任何简单的方法从t
获取substriing(i,j)
?不使用strings
等,只使用char t [200]
。
char* substr(char* arr, int begin, int len)
{
char* res = new char[len + 1];
for (int i = 0; i < len; i++)
res[i] = *(arr + begin + i);
res[len] = 0;
return res;
}
char *sub = t+i;
int len = j-i;
printf("%.*s\n",len,sub);
如果您需要一个不同的子字符串副本,则必须复制。
这应该可以正常工作:
#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];
new
时,还有malloc
? - masoudchar 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;
char const * beg = t+i;
char const * end = t+j+1;
std::cout.write(beg, end-beg);
或者你可以使用一个封装了这个想法的类。标准库中提出了类似于这样的东西。同时,你可以编写自己的类,或者使用库中的一个。例如,llvm::StringRef
。
llvm::StringRef sref(t+i, j+1-i);
std:cout << sref;