views:

668

answers:

5

I wouldn't mind writing my own function to do this but I was wondering if there existed one in the string.h or if there was a standard way to do this.

char *string = "This is a string";

strcut(string, 4, 7);

printf("%s", string); // 'This a string'

Thanks!

A: 

If you are doing this in C and know the offset then it's pretty simple.

char string[] = "my string";
char *substring;
substring = &string[2];

printf("%s", substring);

EDIT: If you wanted to shift the string.

char string[] = "my string";

int i = 0;
int offset = 2;

for( i = 0; string[i+offset] != '\0'; i++ ) {
 string[i] = string[i + offset];
}
string[i] = '\0';
Suroot
I think he wants to eliminate parts of the middle of the string and move the rest to an earlier offset.
Uri
Sorry for missing that, seemed like you just wanted to print out a substring.
Suroot
+1  A: 

If you're talking about getting rid of the middle of the string and moving the rest earlier in place, then I don't think there's a standard library function for it.

The best approach would be to find the end of the string, and then do an O(cut_size) cycle of shifting all the characters to the new location. In fact, there's a similar common interview question.

You have to be careful about using things like memory copy since the destination buffer overlaps with the source.

Uri
+7  A: 

Use memmove to move the tail, then put '\0' at the new end position. Be careful not to use memcpy - its behaviour is undefined in this situation since source and destination usually overlap.

sharptooth
Just allow memmove() to move extra byte with 0-terminator
qrdl
Yeap, that'a good idea.
sharptooth
+2  A: 

You can just tell printf to cut the interesting parts out for you:

char *string = "This is a string";
printf("%.*s%s", 4, string, &string[7]); // 'This a string'

:-)

che
... and then sprintf it into a new variable :-)
TofuBeer
A: 

You may be able to accomplish what you want and avoid writing a new function with a combination of strncpy and strcat:

#include <stdio.h>
#include <string.h>
int main(void)
{
  char   newStr[10];
  char   origStr[] = "This is a string";
  strncpy(newStr, origStr, 4);
  strcat(newStr, &origStr[7]);
  printf("newStr = %s\n", newStr);
  return(0);
}

For me, this outputs "This a string" (quotes mine), using Borland's free command line compiler on Windows XP. You can check out string.h at: http://opengroup.org/onlinepubs/007908799/xsh/string.h.html

PTBNL