I keep trying to test this code but I keep getting a segmentation fault in my power() function. The code is supposed to take a word made up of lowercase letters and change the word to a number of base 10. The word is supposed to take on the form of a number of base 20, where 'a' = 0, 'b' = 1,...., 't' = 19;
int power(int i){
if(i==1){
return 20;
}else{
return 20*power(i--);
}
}
int main(){
int len;
char mayan[6];
int n;
int val;
while(scanf("%s", mayan)){
val = 0;
n = 0;
for(len = 0; mayan[len] != '\0'; len++){
mayan[len] = tolower(mayan[len]);
mayan[len] = mayan[len] - 'a';
}
for(i = 0; len >= 0; len--, i++){
if(mayan[len] <= 19){
n = n + mayan[len] * power(i);
}else{
fprintf(stderr, "Error, not a base 20 input \n");
val = 1;
break;
}
}
if(val==0){
printf("%d \n", n);
}
}
return val;
}
There were three mistakes in your code.
Case for i==0 not added in the power function, which basically translates to any number to the power of zero is one i.e. x^0 = 1;.
Instead of using return 20*power(i--); for your recursive call, use return 20*power(i-1);. i-- is post decrement operator, which means that, it will return the value of i as it is and will the decrement it for further use, which is not what you want. Also, you altogether don't even want to change the value of i for this iteration too; what you want to do is use a value one less than i for the next iteration, which is what, passing i-1, will do.
Add a len-- in the initialization of the for(i = 0; len >= 0; len--, i++) loop, because len is now over the last index of the input because of the previous loop.
Correcting these mistakes the final code is:
#include<stdio.h>
int power(int i)
{
if(i==0)
{
return 1;
}
if(i==1)
{
return 20;
}
else
{
return 20*power(i-1);
}
}
int main()
{
int len,i;
char mayan[6];
int n;
int val;
while(scanf("%s", mayan))
{
val = 0;
n = 0;
for(len = 0; mayan[len] != '\0'; len++)
{
mayan[len] = tolower(mayan[len]);
mayan[len] = mayan[len] - 'a';
}
for(i = 0, len--; len >= 0; len--, i++)
{
if(mayan[len] <= 19)
{
n = n + mayan[len] * power(i);
}
else
{
fprintf(stderr, "Error, not a base 20 input \n");
val = 1;
break;
}
}
if(val==0)
{
printf("%d \n", n);
}
}
return val;
}
Note that, your code would essentially only work for at most a five digit base 20 number, because, the array mayan that you are using to store it has size 6, of which, one character will be spent for storing the terminating character \0. I recommend that you increase the size of the array mayan unless you want to support only five digit base 20 numbers.
Related
Here is the code:
#include <stdio.h> // printf
#include <cs50.h> // get_long
#include <string.h> // strlen
#include <stdlib.h> // stdlib
int credit_test(string input);
int main(void)
{
string userInput;
// Gets user input, and tests if input is valid
bool isInvalid = false;
do
{
userInput = get_string("Number: "); // Prompts user for input
for(int i = 0, evenIndex = strlen(userInput); evenIndex > i; i++)
{
if(userInput[i] - 48 >= 0 && userInput[i] - 48 <= 9 && (strlen(userInput) == 15 || strlen(userInput) == 16)) // Tests if input is valod
{
isInvalid = false;
}
else
{
isInvalid = true;
break;
}
}
}
while(isInvalid);
int keyValidity = credit_test(userInput);
}
int credit_test(string input)
{
int inputLen;
inputLen = strlen(input);
// Even number calculation
int evenArr[16];
int evenSum = 0;
int evenIndex = 0;
printf("Length: %i\n", inputLen);
for(int i = 0; inputLen > i; i++)
{
int n = i * 2;
evenArr[evenIndex] = input[n] * 2;
if(evenArr[evenIndex] > 0)
{
evenArr[evenIndex] -= 96;
}
if(evenArr[evenIndex] > 9) // Code to split doubles
{
int doubleNum = evenArr[evenIndex];
evenArr[evenIndex] = 1;
evenIndex++;
evenArr[evenIndex] = doubleNum % 10;
}
evenIndex++;
evenSum += evenArr[i];
printf("%i\n", evenArr[i]);
printf("Length: %i\n", inputLen);
}
printf("Length: %i\n", inputLen);
printf("Even Sum: %i\n", evenSum);
// Odd number calculation
int oddArr[16];
int oddSum = 0;
int oddIndex = 1;
for(int i = 0; 16 > i; i++)
{
oddArr[i] = input[oddIndex];
if(oddArr[i] > 0)
{
oddArr[i] -= 48;
}
oddSum += oddArr[i];
oddIndex += 2;
printf("%i\n", oddArr[i]);
}
printf("Odd Sum: %i\n", oddSum);
// Validity test
int finalSum = evenSum + oddSum;
int cardType = finalSum % 10;
printf("Final Sum: %i\n", finalSum);
if(cardType == 0 && (input[0] - 48) == 5)
{
printf("MasterCard \n");
}else if (cardType == 0 && (input[0] - 48) == 4)
{
printf("Visa \n");
}else if(cardType == 0 && (input[0] - 48) == 3)
{
printf("Amex \n");
}else
{
printf("Invalid \n");
}
return 0;
}
I just cannot wrap my head around why, but if you run the code, and keep an eye on the "inputLen" variable it stays what it should be, but in the first for loop which gets the even number in the input, the inputLen stays the same, which is correct, but when the loop finishes, for some reason, the variable changes to 0? So would anyone mind to explain as to why its happening? And sorry if the code is all wonky and bad :)
Thanks so much.
This part of the loop
for(int i = 0; inputLen > i; i++)
{
int n = i * 2;
evenArr[evenIndex] = input[n] * 2;
//...
invokes undefined behavior because the expression input[n] can access memory beyond the used array due to using the expression i * 2 as an index. For example then i is equal to inputLen - 1 then n will bi initialized by the expression 2 * ( inputLen - 1 ) and the value of the expression you are using as an index to access elements of the array input but the array does not have so many elements.
Also in this code snippet
if(evenArr[evenIndex] > 9) // Code to split doubles
{
int doubleNum = evenArr[evenIndex];
evenArr[evenIndex] = 1;
evenIndex++;
evenArr[evenIndex] = doubleNum % 10;
}
evenIndex++;
the variable evenIndex can be incremented twice that again can be a reason of undefined behavior when this variable is used as an index to access elements of the array evenArr.
I am self teaching C programming.
I am trying to count number of int present in given string which are separated by space.
exp:
input str = "1 2 11 84384 0 212"
output should be: 1, 2, 11, 84384, 0, 212
total int = 6
When I try. It gives me all the digits as output which make sense since I am not using a right approach here.
I know in python I can use str.split (" ") function which can do my job very quickly.
But I want to try something similar in C. Trying to create my own split method.
#include <stdio.h>
#include <string.h>
void count_get_ints(const char *data) {
int buf[10000];
int cnt = 0, j=0;
for (int i=0; i<strlen(data); i++) {
if (isspace(data[i] == false)
buf[j] = data[i]-'0';
j++;
}
printf("%d", j);
}
// when I check the buffer it includes all the digits of the numbers.
// i.e for my example.
// buf = {1,2,1,1,8,4,3,8,4,0,2,1,2}
// I want buf to be following
// buf = {1,2,11,84384,0,212}
I know this is not a right approach to solve this problem. One way to keep track of prev and dynamically create a memory using number of non space digits encountered.
But I am not sure if that approach helps.
You want to build your number incrementally until you hit a space, then put that into the array. You can do this by multiplying by 10 then adding the next digit each time.
void count_get_ints(const char *data) {
int buf[10000];
int j = 0;
int current_number = 0;
// Move this outside the loop to eliminate recalculating the length each time
int total_length = strlen(data);
for (int i=0; i <= total_length; i++) {
// Go up to 1 character past the length so you
// capture the last number as well
if (i == total_length || isspace(data[i])) {
// Save the number, and reset it
buf[j++] = current_number;
current_number = 0;
}
else {
current_number *= 10;
current_number += data[i] - '0';
}
}
}
I think strtok will provide a cleaner solution, unless you really want to iterate over every char in the string. It has been a while since I did C, so please excuse any errors in the code below, hopefully it will give you the right idea.
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[19] = "1 2 11 84384 0 212";
const char s[2] = " ";
char *token;
int total;
total = 0;
token = strtok(str, s);
while (token != NULL) {
printf("%s\n", token);
total += atoi(token);
token = strtok(NULL, s);
}
printf("%d\n", total);
return 0;
}
You can check the ascii value of each character by doing c-'0'. If it's between [0,9], then it's an integer. By having a state variable, when you're inside an integer by checking if a given character is a number of space, you can keep track of the count by ignoring white space. Plus you don't need a buffer, what happens if data is larger than 10,000, and you write pass the end of the buffer?, undefined behavior will happen. This solution doesn't require a buffer.
Edit, the solution now prints the integers that are in the string
void count_get_ints(const char *data) {
int count = 0;
int state = 0;
int start = 0;
int end = 0;
for(int i = 0; i<strlen(data); i++){
int ascii = data[i]-'0';
if(ascii >= 0 && ascii <= 9){
if(state == 0){
start = i;
}
state = 1;
}else{
//Detected a whitespace
if(state == 1){
count++;
state = 0;
end = i;
//Print the integer from the start to end spot in data
for(int j = start; j<end; j++){
printf("%c",data[j]);
}
printf(" ");
}
}
}
//Check end
if(state == 1){
count++;
for(int j = start; j<strlen(data); j++){
printf("%c",data[j]);
}
printf(" ");
}
printf("Number of integers %d\n",count);
}
I believe the standard way of doing this would be using sscanf using the %n format specifier to keep track of how much of the string is read.
You can start with a large array to read into -
int array[100];
Then you can keep reading integers from the string till you can't read anymore or you are done reading 100.
int total = 0;
int cont = 0;
int ret = 1;
while(ret == 1 && total < 100) {
ret = sscanf(input, "%d%n", &array[total++], &cont);
input += cont;
}
total--;
printf("Total read = %d\n", total);
and array contains all the numbers read.
Here is the DEMO
Example using strtol
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <ctype.h>
int count_get_ints(int output[], int output_size, const char *input) {
const char *p = input;
int cnt;
for(cnt = 0; cnt < output_size && *p; ++cnt){
char *endp;
long n;
errno = 0;
n = strtol(p, &endp, 10);
if(errno == 0 && (isspace((unsigned char)*endp) || !*endp) && INT_MIN <= n && n <= INT_MAX){
output[cnt] = n;
while(isspace((unsigned char)*endp))
++endp;//skip spaces
p = endp;//next parse point
} else {
fprintf(stderr, "invalid input '%s' in %s\n", p, __func__);
break;
}
}
return cnt;
}
int main(void) {
const char *input = "1 2 11 84384 0 212";
int data[10000];
int n = sizeof(data)/sizeof(*data);//number of elements of data
n = count_get_ints(data, n, input);
for(int i = 0; i < n; ++i){
if(i)
printf(", ");
printf("%d", data[i]);
}
puts("");
}
Assuming you don't have any non-numbers in your string, you can just count the number of spaces + 1 to find the number of integers in the string like so in this pseudo code:
for(i = 0; i < length of string; i++) {
if (string x[i] == " ") {
Add y to the list of strings
string y = "";
counter++;
}
string y += string x[i]
}
numberOfIntegers = counter + 1;
Also, this reads the data between the white spaces. Keep in mind this is pseudo code, so the syntax is different.
i'm newbie in C programming .
i have written this code for adding two numbers with 100 digits , but i don't know why the code does not work correctly , it suppose to move the carry but it doesn't .
and the other problem is its just ignoring the first digit (most significant digit) .
can anybody help me please ?
#include <stdio.h>
#include <ctype.h>
int sum[101] = {0};
int add(int a, int b);
void main()
{
static int a[100];
static int b[100];
char ch;
int i = 0;
int t;
for (t = 0; t != 100; ++t)
{
a[t] = 0;
}
for (t = 0; t != 100; ++t)
{
b[t] = 0;
}
do
{
ch = fgetc(stdin);
if ( isdigit(ch) )
{
a[i] = ch - 48;
++i;
}
else
break;
}
while (ch != '\n' || i == 100 || i != '\0');
i = 0;
do
{
ch = fgetc(stdin);
if ( isdigit(ch) )
{
b[i] = ch - 48;
++i;
}
else
break;
}
while (ch != '\n' || i == 100 || i != '\0');
for (;i!=0; --i)
{
add(a[i], b[i]);
}
for (i==0;i != 101; ++i)
{
printf("%d", sum[i]);
}
}
int add( int a , int b)
{
static int carry = 0;
float s = 0;
static int p = 101;
if (0 <= a+b+carry <= 9)
{
sum[p] = (a + b + carry);
carry = 0;
--p;
return 0;
}
else
{
if (10 <= a+b+carry < 20)
{
s = (((a+b+carry)/10.0 ) - 1) * 10 ;
carry = ((a+b+carry)/10.0) - (s/10);
}
else
{
s = (((a+b+carry)/10 ) - 2) * 10;
carry = ((a+b+carry)/10.0) - (s/10);
}
sum[p] = s;
--p;
return 0;
}
}
Your input loops have serious problem. Also you use i to count the length of both a and b, but you don't store the length of a. So if they type two numbers that are not equal length then you will get strange results.
The losing of the first digit is because of the loop:
for (;i!=0; --i)
This will execute for values i, i-1, i-2, ..., 1. It never executes with i == 0. The order of operations at the end of each iteration of a for loop is:
apply the third condition --i
test the second condition i != 0
if test succeeded, enter loop body
Here is some fixed up code:
int a_len;
for (a_len = 0; a_len != 100; ++a_len)
{
int ch = fgetc(stdin); // IMPORTANT: int, not char
if ( ch == '\n' || ch == EOF )
break;
a[a_len] = ch;
}
Similarly for b. In fact it would be a smart idea to make this code be a function, instead of copy-pasting it and changing a to b.
Once the input is complete, then you could write:
if ( a_len != b_len )
{
fprintf(stderr, "My program doesn't support numbers of different length yet\n");
exit(EXIT_FAILURE);
}
for (int i = a_len - 1; i >= 0; --i)
{
add(a[i], b[i]);
}
Moving onto the add function there are more serious problems here:
It's not even possible to hit the case of sum being 20
Do not use floating point, it introduces inaccuracies. Instead, doing s = a+b+carry - 10; carry = 1; achieves what you want.
You write out of bounds of sum: an array of size [101] has valid indices 0 through 100. But p starts at 101.
NB. The way that large-number code normally tackles the problems of different size input, and some other problems, is to have a[0] be the least-significant digit; then you can just expand into the unused places as far as you need to go when you are adding or multiplying.
I have a problem at the add2_recur function. I am trying to add up a single character digit within a string. But I do not know how to return a string to my main function so I can print out the result. I try using function pointer but i only return the first value of the string.
Any suggestion on how to do this would be helpful.
//check if string is valid
int digcheck_helper(char *theno, int start, int length) {
int charToInt = *(theno+start);
if(!((charToInt >= 48) &&(charToInt <= 57)))
return 0;
if(length == 0)
return 1;
return digcheck_helper(theno,start+1,length-1);
}
int digcheck(char *str, int start, int length) {
return digcheck_helper(string,start,length);
}
/**********************
****add recursive function**/
void add2_recur(char *num1, char *num2, int start, int carryDig) {
int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
char *str = (char*) malloc(strlen(num1) + 2);
sum = singleChar1 + singleChar - 96;
if(carryDig == 1)
sum = sum + 1;
if(start < strlen(num1)) {
if(sum >= 10) {
sum = sum - 10;
str[start] = sum + 48;
carryDig = 1;
printf("sum of single digit is: %c\n", str[start]);
}
else if( sum < 10) {
str[start] = sum + 48;
carryDig = 0;
printf("sum of single digit is: %c\n", str[start]);
}
add2_recur(num1,num2,start+1,carryDig);
}
else if ((start == strlen(num1)) && (carryDig ==1)){
str[start+1] = 48;
printf("sum of single digit is: %c\n", str[start+1]);
}
}
void add2(char *n1, char *n2) {
add2_recur(n1,n2,0,0)
}
/*******************/
int main() {
char string1[20000], string2[20000], revStr1[20000], revStr2[20000];
int digit_1, digit_2, i;
printf("Enter first number >");
fgets(string1,20000,stdin);
string1[strlen(string1)-1] = '\0';
digit_1 = digcheck(string1,0,strlen(string1)-1);
//Check if string is valid integer
if(digit_1 = 0)
printf("This number is invalid\n");
else{
printf("Enter second number >");
fgets(string2,2000,stdin);
string2[strlen(string2)-1] = '\0';
digit_2 = digcheck(string2,0,strlen(string2-1);
if(digit_2 == 0)
printf("This number is invalid\n");
else
printf("1st num is %s\n2st num is %s\n", string1, string2);
}
// reverse string
for(i=0;i<strlen(string1);i++)
revStr1[i] = string1[(strlen(string1)-1) - i];
for(i=0;i,strlen(string2);i++)
revStr2[i] = string2[(strlen(string2) -1) - i];
// compare string and pass to add2
if(strlen(revStr1) < strlen(revStr2)) {
for(i = strlen(revStr1); i < strlen(revStr2); i++)
revStr1[i] = '0';
add2(revStr1,revStr2);
}
else if(strlen(revStr2) < strlen(revStr1)) {
for(i = strlen(revStr2); i < strlen(revStr1); i++)
revStr2[i] = '0';
add2(revStr1,revStr2);
}
else
add2(revStr1,revStr2);
return 0;
}
In C something like this is typically achieved by not returning the actual string. Instead you can just work with a pointer to a buffer passed to you. Use the actual return value to report status messages instead.
To not spoil the actual task for you, let's define a simple recursive function that will return a string with all non-alphanumerical characters being stripped:
#include <stdio.h>
#include <string.h>
int strip_stuff_rec(const char *input, char *output, unsigned int offset_input, unsigned offset_output) {
// Retrieve the character and move the offset
const char c = input[offset_input++];
if (c == '\0') { // Terminator; we're done!
// Terminate the output string
output[offset_output] = '\0';
return 1; // Signal success
}
// Character is alphanumeric?
if (isalnum(c)) {
// Append the character to our result and move the offset
output[offset_output++] = c;
}
// To have an error case, let's just pretend the string must not include #!
if (c == '#') {
return 0; // Signal an error
}
// Now handle the next position
return strip_stuff_rec(input, output, offset_input, offset_output);
}
int strip_stuff(const char *input, char *output) {
// Reset the output
output[0] = '\0';
// Start the recursive calls
return strip_stuff_rec(input, output, 0, 0);
}
int main(int argc, char **argv) {
// First let's set some input string
const char *input = "Hello World! -- I've had a wonderful day!";
// And we'll need a buffer for our result
char result[256];
// Now call the function and check the return value to determine
// whether it's been successful.
if (strip_stuff(input, result) == 0) {
printf("Some error happened!\n");
}
else {
printf("The stripped string is '%s'.\n", result);
}
}
this function:
void add2(char *n1, char *n2)
{
add2_recur(n1,n2,0,0)
}
this function has a couple of problems.
1) it will not compile because the statement that calls add2-recur()
is missing a trailing ';'
2) this function is not needed as add2_recur can be called directly
3) this is expected to add two numbers together ..
How is it to return the result?
It (probably) should be more like:
void add2(char *n1, char *n2, char *sum)
{
strcpy(sum, add2_recur(n1,n2,0,0) );
}
ok, i fix the code by creating a pointer function and storing the value into the str array by using malloc. I commented out the code. But it still only return the first element of the array to the main function from the heap. How do i get it to return the whole array?
//check if string is valid
int digcheck_helper(char *theno, int start, int length) {
int charToInt = *(theno+start);
if(!((charToInt >= 48) &&(charToInt <= 57)))
return 0;
if(length == 0)
return 1;
return digcheck_helper(theno,start+1,length-1);
}
int digcheck(char *str, int start, int length) {
return digcheck_helper(string,start,length);
}
/**********************
****add recursive function**/
char *add2_recur(char *num1, char *num2, int start, int carryDig) {
int singleChar1 = *(num1 + start), singleChar2 = *(num2 + start);
char *str = (char*) malloc(strlen(num1) + 2), sum;
sum = singleChar1 + singleChar - 96;
if(carryDig == 1)
sum = sum + 1;
if(start < strlen(num1)) {
if(sum >= 10) {
sum = sum - 10;
str[start] = sum + 48; //store value in each element of an array
carryDig = 1;
printf("sum of single digit is: %c\n", str[start]);
}
else if( sum < 10) {
str[start] = sum + 48; //store value in each element of an array
carryDig = 0;
printf("sum of single digit is: %c\n", str[start]);
}
add2_recur(num1,num2,start+1,carryDig);
}
else if ((start == strlen(num1)) && (carryDig ==1)){
str[start+1] = 49; // store value in each element of an array
printf("sum of single digit is: %c\n", str[start+1]);
}
return str;
}
/*******************/
int main() {
char string1[20000], string2[20000], revStr1[20000], revStr2[20000], *addResult;
int digit_1, digit_2, i;
printf("Enter first number >");
fgets(string1,20000,stdin);
string1[strlen(string1)-1] = '\0';
digit_1 = digcheck(string1,0,strlen(string1)-1);
//Check if string is valid integer
if(digit_1 = 0)
printf("This number is invalid\n");
else{
printf("Enter second number >");
fgets(string2,2000,stdin);
string2[strlen(string2)-1] = '\0';
digit_2 = digcheck(string2,0,strlen(string2-1);
if(digit_2 == 0)
printf("This number is invalid\n");
else
printf("1st num is %s\n2st num is %s\n", string1, string2);
}
// reverse string
for(i=0;i<strlen(string1);i++)
revStr1[i] = string1[(strlen(string1)-1) - i];
for(i=0;i,strlen(string2);i++)
revStr2[i] = string2[(strlen(string2) -1) - i];
// compare string and pass to add2
if(strlen(revStr1) < strlen(revStr2)) {
for(i = strlen(revStr1); i < strlen(revStr2); i++)
revStr1[i] = '0';
add2(revStr1,revStr2);
}
else if(strlen(revStr2) < strlen(revStr1)) {
for(i = strlen(revStr2); i < strlen(revStr1); i++)
revStr2[i] = '0';
addResult = add2(revStr1,revStr2);
}
else
addResult = add2(revStr1,revStr2);
// print out
printf("sum is: %s\n", addResult);
return 0;
Since passing the whole array is not very optimal, C usually in most of the expressions convert it to pointer.
One way to pass whole array is by enclosing it in a struct. (Not a good solution though)
typedef struct
{
char s[128];
}MYSTR;
I'm trying to create a function that, given two C strings, it spits back the number of consecutive character overlap between the two strings.
For example,
String 1: "Today is monday."
String 2: " is monday."
The overlap here would be " is monday.", which is 11 characters (it includes the space and '.').
If you need something more efficient, consider that a partial mismatch between Strings 1 and 2 means you can jump the length of the remainder of String 2 along String 1. This means you don't need to search the entirety of String 1.
Take a look at the Boyer-Moore algorithm. Though it is used for string searching, you could implement this algorithm for finding the maximum-length substring using String 2 as your pattern and String 1 as your target text.
There is probably a more efficient way to do this, but here's a simple approach:
#include <string.h>
int main() {
char s1[17] = "Today is monday.";
char s2[12] = " is monday.";
int max = 0;
int i_max = -1;
int j_max = -1;
int i = 0, j = 0, k=0;
int endl = 0, sl1, sl2;
char *ss1, *ss2;
for(i = 0; i < strlen(s1)-1; i++) {
ss1 = s1+i;
sl1 = strlen(ss1);
if(max >= sl1) {
break; // You found it.
}
for(j = 0; j < strlen(s2)-1; j++) {
ss2 = s2+j;
sl2 = strlen(ss2);
if(max >= sl2) {
break; // Can't find a bigger overlap.
}
endl = (sl1 > sl2)?sl2:sl1;
int n_char = 0;
for(k = 0; k < endl+1; k++) {
// printf("%s\t%s\n", ss1+k, ss2+k); // Uncomment if you want to see what it compares.
if(ss1[k] != ss2[k] || ss1[k] == '\0') {
n_char = k;
break;
}
}
if(n_char > max) {
max = n_char;
i_max = i;
j_max = j;
}
}
}
char nstr[max+1];
nstr[max] = '\0';
strncpy(nstr, s1+i_max, max);
printf("Maximum overlap is %d characters, substring: %s\n", max, nstr);
return 0;
}
Update: I have fixed the bugs. This definitely compiles. Here is the result: http://codepad.org/SINhmm7f
The problems were that endl was defined wrong and I wasn't checking for end-of-line conditions.
Hopefully the code speaks for itself.
Here is my solution, it will return the position of the overlap starting point, it's a bit complex, but that's how it's done in C:
#include <string.h>
int FindOverlap (const char * a, const char * b)
{
// iterators
char * u = a;
char * v = b;
char * c = 0; // overlap iterator
char overlapee = 'b';
if (strlen(a) < strlen(b)) overlapee = 'a';
if (overlapee == 'b')
{
while (*u != '\0')
{
v = b; // reset b iterator
c = u;
while (*v != '\0')
{
if (*c != *v) break;
c++;
v++;
}
if (*v == '\0') return (u-a); // return overlap starting point
}
}
else if (overlapee == 'a')
{
while (*v != '\0')
{
u = a; // reset b iterator
c = v;
while (*u != '\0')
{
if (*c != *u) break;
c++;
u++;
}
if (*v == '\0') return (v-b); // return overlap starting point
}
}
return (-1); // not found
}