The substring char [] in C ++

I have

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

Is there an easy way to get substriing(i,j)from tnext to copying each element into a separate array? No stringsetc. Simple char t[200].

+5
source share
6 answers

If you are allowed to change t, you can set t[j]to 0and then use t + ito get a substring.

If not, you will have to make a copy.

However, why can't you just use std::stringand keep yourself a headache?

+5
source

If you only need to read the data, then t + i is what you want, alas, you have to control the length of your substring ...

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

If you need a separate copy of the substring, you must copy.

+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];
+2

.

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

Or you can use a class that encapsulates this idea. For the standard library, something like this is suggested . In the meantime, you can write your own, or you can use it in the library. Eg llvm::StringRef.

llvm::StringRef sref(t+i, j+1-i);
std:cout << sref;
+1
source

This does not check boundaries to ensure that the destination array is large enough.

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;
0
source
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;
}
0
source

All Articles