Reputation: 3479
I have two strings, e.g.:
str1 = "aaabbbcccdddeee"
str2 = "aaabbbccc"
How to do something like str1 - str2
to get the dddeee
substring?
Upvotes: 1
Views: 144
Reputation: 34284
Since you have clarified that str2
is a prefix of str1
, you can get the pointer to the extra part in str2
simply with the operation:
str1 + strlen(2);
For example, to print the "dddeee" part of your string:
printf("%s\n", str1 + strlen(str2));
How this works is simple. str1 + strlen(str2)
is a pointer that is strlen(str2)
N characters away from the beginning of the string pointed to be str1
. strlen(str2)
returns the number of characters in the second string and you skip those many characters in the first string and reach the extra part.
Upvotes: 1
Reputation: 272657
If str2
is guaranteed to be a prefix of str1
, then this will suffice:
const char *str3 = &str1[strlen(str2)];
which is equivalent to this: (as @James points out in the comments)
const char *str3 = str1 + strlen(str2);
Of course, str3
is just a pointer into one of the original strings. If the contents of the original string changes, then so will your result. So you may want to create a copy, using malloc()
and strcpy()
(and then free()
at some point).
Upvotes: 5
Reputation: 122001
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[] = "aaaabbbbbdddeee";
char b[] = "aaaabbbbb";
const char* start = strstr(a, b);
if (start)
{
printf("%s\n", a + strlen(b));
}
return 0;
}
Upvotes: 1
Reputation: 2278
str3 will contain a copy of the prefix:
str1 = "aaabbbcccdddeee"
str2 = "aaabbbccc"
size_t length = strlen1 - strlen2;
char* str3 = calloc(sizeof(char), length + 1);
memcpy(str3, str1+strlen(str2), length);
Upvotes: 1
Reputation: 726809
This will skip the common prefix of two strings:
char* suffix(const char* prefix, const char* str) {
while (*prefix && *str && *prefix == *str) {
prefix++;
str++;
}
return str;
}
For example, if you pass "AAB"
and "AACC"
, this would return "CC"
.
Upvotes: 2