Which string is the longest - c

My code:
What I'm trying to do is to input two strings, then return the longest one. If they're the same length then return NULL. Now, the code is just outputting gibberish and I cannot find out why. The function returns a pointer to the first character of the largest string. Then it goes through the while loop, and I'm trying to dereference the pointer and print out its value.
Note: I'm revising for an exam and we have to use only pointers and not treat strings as arrays.
#include<stdio.h>
char* string_ln(char*, char*);
int main() {
char str1[20];
char str2[20];
char* length;
scanf("%s%s", str1, str2);
length = string_ln(str1, str2);
while (length != '\0') {
printf("%c", *length);
length++;
}
}
char* string_ln(char*p1, char*p2) {
int count1 = 0;
while (*p1 != '\0') {
count1++;
p1++;
}
int count2 = 0;
while (*p2 != '\0') {
count2++;
p2++;
}
if (count1 > count2) {
return p1;
}
else if (count2 > count1) {
return p2;
}
else {
return NULL;
}
}

In writing string_ln you iterate over both strings completely to find their lengths, and then compare those numbers. This can work, but you don't actually need to do this. You only need to know which is longer. It doesn't matter how much longer the longer string is.
char *string_ln(char *str1, char *str2) {
char *iter1, *iter2;
for (iter1 = str1, iter2 = str2;
*iter1 && *iter2;
iter1++, iter2++);
if (!(*iter1 || *iter2)) {
return NULL;
}
else if (*iter1) {
return str1;
}
else {
return str2;
}
}
We simply need to iterate over both strings, until at least one hits a NULL character. Once we get to that point, we can test to see which iterator is NULL. If it's both of them, then they're the same length. If the first iterator is not NULL, then the first string is longer. Otherwise, the second string is longer.
The benefit to this approach is that we avoid unnecessary work, and make it much quicker to compare strings of very different lengths.

There are a few problems here. First, you're modifying p1 and p2 in the function, so you won't actually return a pointer to the beginning of the largest string, but to its end. One way to avoid this is to iterate over copies of p1 and p2:
char* string_ln(char*p1, char*p2)
{
char* tmp1 = p1;
int count1 = 0;
while (*tmp1 != '\0') {
count1++;
tmp1++;
}
char* tmp2 = p2;
int count2 = 0;
while (*tmp2 != '\0') {
count2++;
tmp2++;
}
if(count1>count2){
return p1;
}
else if(count2>count1){
return p2;
}
else{
return NULL;
}
}
Second, in your main, you're using the %c format string, which works for a single char, not a whole string. Since you have a string anyway, you can avoid a format string and just print it directly. Also, note that you should explicitly check for NULLs:
int main() {
char str1[20];
char str2[20];
char* longest;
scanf("%s%s", str1, str2);
longest = string_ln(str1, str2);
if (longest) {
printf(longest);
} else {
printf("They are the same length");
}
}

I think you're missing to dereference the pointer. Instead of
while(length!='\0')
you'd need
while(*length!='\0')
That said, in the called function, you're reuring pointers after the increment, i.e., the returned pointers do not point to the start of the string anymore. You need to ensure that you return pointers which points to the beginning of the string. You can change your code to
int count1 = 0;
while (p1[count1] != '\0') {
count1++;
}
int count2 = 0;
while (p2[count2] != '\0') {
count2++;
}
so that p1 and p2 does not change.

For starters the function should be declared like
char * string_ln( const char *, const char * );
because the passed strings are not being changed within the function.
You are returning from the function the already modified pointer p1 or p2 that is being changed in one of the while loops
while (*p1 != '\0') {
count1++;
p1++;
}
while (*p2 != '\0') {
count2++;
p2++;
}
So the returned pointer points to the terminating zero '\0' of a string.
Moreover in main before this while loop
length = string_ln(str1, str2);
while(length!='\0'){
printf("%c", *length);
length++;
}
you are not checking whether the pointer length is equal to NULL. As a result the program can invoke undefined behavior.
The function itself can be defined the following way using only pointers.
char * string_ln( const char *p1, const char *p2 )
{
const char *s1 = p1;
const char *s2 = p2;
while ( *s1 != '\0' && *s2 != '\0' )
{
++s1;
++s2;
}
if ( *s1 == *s2 )
{
return NULL;
}
else if ( *s1 == '\0' )
{
return ( char * )p2;
}
else
{
return ( char * )p1;
}
}
and in main you need to write
char *length = string_ln( str1, str2 );
if ( length != NULL )
{
while ( *length )
printf( "%c", *length++ );
}
Pay attention to that the return type of the function is char * instead of const char *. It is because in C there is no function overloading and the returned pointer can point to a constant string or to a non-constant string. It is a general convention in C for declaring string functions.

Related

Replace a word in string

How do i make below program work properly, The main problem i have seen so far is str1 is not defined properly which may be the real cause for the program not working properly.
#include<stdio.h>
#include<string.h>
int main()
{
char string[]="We will rock you";
char s1[10],s2[10];
printf("Enter string 1 ");
gets(s1);
printf("Enter string 2 ");
gets(s2);
int start,end,compare;
for(int i=0;string[i]!='\0';i++)
if(string[i]==s1[0])
{
start=i;
break;
}
//printf("%d",start);
end=start+strlen(s1);
//printf("\n%d",end);
char str1[30],check[10];
//Defining string 1
for(int i=0;i<start;i++)
str1[i]=string[i];
//printf("\n%sd",str1);
//Defining check
for(int i=start;i<end;i++)
check[i-start]=string[i];
//printf("\n%s\n",check,str1);
compare=strcmp(check,s1);
//printf("\n%d",compare);
if(compare==0)
strcat(str1,s1);
printf("\n%s",str1);
for(int i=end,j=strlen(str1);i<strlen(string);i++)
{
str1[j]=string[i];
}
strcpy(string,str1);
printf("\n%s",string);
}
I know this is not the best way to do it, it has so many loopholes as it wont work for words appearing again and it may also change words like (ask, task or asking) if str1 is given ask.
But still help me , What am i doing wrong???
What am i doing wrong???
For starters the function gets is unsafe and is not supported by the C Standard. Instead either use scanf or fgets.
If in this for loop
int start,end,compare;
for(int i=0;string[i]!='\0';i++)
if(string[i]==s1[0])
{
start=i;
break;
}
the condition string[i]==s1[0] does not evaluate to true then the variable start will have an indeterminate value because it is not initialized and all the subsequent code after the for loop invokes undefined behavior because there is used the uninitialized variable start.
If the condition evaluates to true then the value of end
end=start+strlen(s1);
can be larger than the length of the original string string. That again can invoke undefined behavior in this for loop
for(int i=0;i<start;i++)
str1[i]=string[i];
After this for loop
for(int i=start;i<end;i++)
check[i-start]=string[i];
//printf("\n%s\n",check,str1);
compare=strcmp(check,s1);
the array check does not contain a string. So calling the function strcmp also invokes undefined behavior.
It seems that in this call there is at least a typo.
if(compare==0)
strcat(str1,s1)
it seems you mean
strcat( str1, s2 );
^^^
If s1 was not found in string then this loop
for(int i=end,j=strlen(str1);i<strlen(string);i++)
{
str1[j]=string[i];
}
just does not make a sense.
Pay attention to that in general the length of s2 can be greater than the length of s1. In this case you may not change s1 to s2 within string declared like
char string[]="We will rock you";
because that results in accessing memory outside the array.
Function replacing string in the string.
char *strreplace(char *haystack, const char *needle, const char *replace, char *buff)
{
int length = strlen(haystack);
int needlelength = strlen(needle);
int replacelength = strlen(replace);
char *ptr = buff;
char *start, *source, *dest;
if (buff == NULL)
{
ptr = malloc((length + 1) * sizeof(char));
source = ptr;
dest = haystack;
}
else
{
source = haystack;
dest = buff;
}
if (ptr != NULL)
{
if (buff == NULL) strcpy(ptr, haystack);
else
{
if (!length)
{
*buff = 0;
}
}
while (needlelength && *source)
{
size_t chunklen;
char *result;
start = source;
if ((result = strstr(source, needle)) == NULL)
{
strcpy(dest, source);
break;
}
chunklen = result - start;
strncpy(dest, start, chunklen);
dest += chunklen;
strcpy(dest, replace);
dest += replacelength;
source = result;
source += needlelength;
}
if (buff == NULL)
{
free(ptr);
ptr = haystack;
}
else
{
ptr = buff;
}
}
return ptr;
}
Hello and Sorry for bad English.
I think this code can help you
char* replace ( char text[] , char mainchar, char replace_char )
{
char out [120];
char* out_pointer = out ;
register char index_2=0;
for ( register char index_1 = 0 ; index_1 < strlen (text) ; ++index_1 )
{
if ( text[index_1] != mainchar )
{
out_pointer[index_2]=text[index_1];
++index_2 ;
}
else
{
out_pointer[index_2]=replace_char;
++index_2 ;
}
}
return out_pointer;
}
To use this function in your source code, proceed as follows :
#include <stdio.h>
#include <string.h>
int main ()
{
char* replace ( char text[] , char mainchar, char replace_char )
{
char out [120];
char* out_pointer = out ;
register char index_2=0;
for ( register char index_1 = 0 ; index_1 < strlen (text) ; ++index_1 )
{
if ( text[index_1] != mainchar )
{
out_pointer[index_2]=text[index_1];
++index_2 ;
}
else
{
out_pointer[index_2]=replace_char;
++index_2 ;
}
}
return out_pointer;
}
char Array[100];
strcpy (Array, replace("Hello", 'H', 'e'));
printf ("%s", Array);
}

Recreate the strstr() function

Hello i am trying to make my own strstr() function and i can't figure out why it is returning a segmentation fault.I am trying to search a string within another string and then return a pointer to the first 'same' letter. Any help would be appreciated.
This is my code:
char* ms_search(char *Str1,char* Str2){
char* p = NULL;
int i,k=0,j = 0;
for(i = 0;i < ms_length(Str1); i++){
if(Str1[i] == Str2[k]){
if(k == 0){
p = &Str1[i];
j= i;
}
if(k == ms_length(Str2)){
break;
}
k++;
}
else{
if(Str1[i] == Str2[0]){
p = &Str1[i];
k=1;
j= i;
}
else{
j=0;
k = 0;
p = NULL;
}
}
}
if(p != NULL){
Str1[ms_length(Str2)+1] = '\0';
}
return &Str1[j];
}
int main(){
int i;
char* p2;
char* p="lolaaa";
char* p1= "aaa";
//char ar2[] = "aaa4";
//ms_copy(p,p1);
//printf("%s",p);
//ms_nconcat(p,p1,3);
//if(ms_ncompare(p,p1,3) == 1) printf("einai idia");
p2 = ms_search(p,p1);
printf("%s",p2);
return 0;
}
Hello i am trying to make my own strstr()
First of all you have to follow the C standard.
The C89/C99 prototype is:
char *strstr(const char *s1, const char *s2);
Standard strstr() function will NOT change the passed buffers.
The functionality is described as:
strstr() function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.
The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.
In standard C, this can be implemented as:
#include <string.h> /* size_t memcmp() strlen() */
char *strstr(const char *s1, const char *s2)
{
size_t n = strlen(s2);
while(*s1)
if(!memcmp(s1++,s2,n))
return (char *) (s1-1);
return 0;
}
The standalone implementation is given below:
#include <stdio.h>
char *strstr1(const char *str, const char *substring)
{
const char *a;
const char *b;
b = substring;
if (*b == 0) {
return (char *) str;
}
for ( ; *str != 0; str += 1) {
if (*str != *b) {
continue;
}
a = str;
while (1) {
if (*b == 0) {
return (char *) str;
}
if (*a++ != *b++) {
break;
}
}
b = substring;
}
return NULL;
}
int main (void)
{
char string[64] ="This is a test string for testing strstr";
char *p;
p = strstr1 (string,"test");
if(p)
{
printf("String found:\n" );
printf ("First occurrence of string \"test\" in \"%s\" is:\n%s", string, p);
}
else
{
printf("String not found!\n" );
}
return 0;
}
Output:
String found:
First occurrence of string "test" in "This is a test string for testing strstr" is:
test string for testing strstr
Your standalone strstrl is correct.
I have my preferences, and you have yours.
Neither is perfect.
You prefer
if ( *b == 0 ) {
return (char *) s1;
}
I prefer
if ( ! *b ) return (char *) s1;
You prefer
str += 1;
I prefer
str++;
You prefer
while (1)
I prefer
for (;;)
If I rewrite your strstrl with my preferences, we get
char *strstr1(const char *str, const char *substring)
{
const char *a, *b = substring;
if ( !*b ) return (char *) str;
for ( ; *str ; str++) {
if (*str != *b) continue;
a = str;
for (;;) {
if ( !*b ) return (char *) str;
if (*a++ != *b++) break;
}
b = substring;
}
return NULL;
}
Note that this version has the same snippet
if ( ! *b ) return (char *) str;
in two locations. Can we rearrange to do that test only once?
Note how we do two tests when lead character matches
if ( *str != *b )
and again later for the same lead char
a = str ; if ( *a++ != *b++)
Can we rearrange that to do a single test?
My rewrite of your standalone strstr is below. It might not be
your style, but it is in many ways similar to your standalone strstr.
My rewrite is shorter and, I want to believe, easier to understand.
char *strstr(const char *str, const char *substring)
{
const char *a = str, *b = substring;
for (;;) {
if ( !*b ) return (char *) str;
if ( !*a ) return NULL;
if ( *a++ != *b++) { a = ++str; b = substring; }
}
}

strchr implementation in c is it possible to make this work?

please help me out , I'm trying to implement strchr and I still get Null when I run this code... what is it wrong with it?
char *ft_strchr(const char *str, int c)
{
int i;
char *temp;
i = 0;
while (str[i])
{
if (str[i] == c)
{
*temp = str[i];
return (temp);
}
else
return (NULL);
i++;
}
return (str);
}
char* ft_strchr(const char *str, int c){
size_t i;
char *temp;
i = 0;
while (str[i])
{
if (str[i] == c)
{
temp = &str[i];
return temp;
}
i++;
}
if(str[i]==c)
{
return &str[i];
}
return NULL;
// You need to return NULL after scanning whole line..
// Or it will send NULL checking after 1st character
}
strchr is supposed to return a pointer to the matching character in the string. You're returning a pointer, but it doesn't point into the string. You never initialized it, so it doesn't point anywhere.
Change
*temp = str[i];
to:
temp = &str[i];
the following code:
makes use of the fact the C passes by value rather than by reference
eliminates the code clutter,
uses a for() statement so the compiler handles all the loop details,
eliminates all the code clutter
Note: this kind of expression: *str evaluates to true, except when the char pointed at is '\0'.
So the below code walks through the passed in char string, terminating on either of two conditions.
1) a matching char is found in the string or
2) end of string is encountered.
The return statement returns NULL if end of string is encountered, else returns the address of where the matching char is first found in the string.
char *ft_strchr(const char *str, int c)
{
for( ; *str && (*str != c); str++ ) ;
return ( *str? str : NULL);
}

concatinate two String Using pointer in C

I'm trying to concatenate two strings using pointer in C, but it doesn't work 100%. At the end of the output String, many unknown characters appear...
char* concat_string (char* s1, char* s2) {
char *s;
int k=0;
s=(char *)malloc((strlen(s1)+strlen(s2))*sizeof(char));
while (*s1!='\0') {
*(s+k)=*s1;
k++;
s1++;
}
while (*s2!='\0') {
*(s+k)=*s2;
k++;
s2++;
}
return s;
}
int main () {
char *ch1, *ch2, *s;
char cch1[10], cch2[10];
printf("ch1 ? ");
scanf("%s",cch1);
printf("ch2 ? ");
scanf("%s",cch2);
ch1=cch1;
ch2=cch2;
s=concat_string(ch1, ch2);
printf("\n%s + %s = ", ch1, ch2);
while (*s!='\0') {
printf("%c", *s);
s++;
}
}
You're not including space for the terminator in the concatenated result. This:
s=(char *)malloc((strlen(s1)+strlen(s2))*sizeof(char));
should be:
s = malloc(strlen(s1) + strlen(s2) + 1);
You're not copying the terminator either, which explains the result you're seeing.
Also, don't cast malloc()'s return value in C, and make your input strings const.
Your code is very hard to read. The use of an integer indexing variable instead of just using pointers makes it needlessly complicated. For reference, here's how I would write it:
char * concat_string(const char *s1, const char *s2)
{
char *s = malloc(strlen(s1) + strlen(s2) + 1);
if(s != NULL)
{
char *p = s;
while((*p++ = *s1++) != '\0');
--p;
while((*p++ = *s2++) != '\0');
}
return s;
}
This is of course still somewhat terse, but I'd argue it's more readable than your version.
printf expects null terminated strings. Otherwise, it will print whatever characters in memory until it hits one. Your concat_string function doesn't put a null terminator on the string.
char* concat_string (char* s1, char* s2){char *s;int k=0;
s=(char *)malloc((strlen(s1)+strlen(s2))*sizeof(char));
while(*s1!='\0'){*(s+k)=*s1;k++;s1++; }
while(*s2!='\0'){*(s+k)=*s2;k++;s2++;}
*(s+k) = 0;
return s;
}
Also, this function is already written for you, just try using strcat.

implementation of strstr() function

The code says at many places "invalid indirection".Please help.
int main()
{
char *s1,*s2,*position;
printf("Enter string:\n");
gets(s1);
printf("Enter word to find:\n");
gets(s2);
*position=ststr(*s1,*s1);
if(*position)
printf("word is found at %c loc\n",*position);
else
printf("word not found");
getch();
return 0;
}
char *strstr(char *s1,char *s2)
{
int flag=1;
char i,j;
for(i=0; ;i++)
{
if(*s1[i]==*s2[0])
for(j=i;*s2;j++)
{
if(*s1[j]!=*s2[j])
flag=0;
}
}
if(flag)
return i;
else
return 0;
}
First, s1 and s2 in main have not been initialized to point anywhere meaningful. Either declare them as static arrays, or allocate memory to them at runtime using malloc() or calloc():
#define SIZE 20 // or some number big enough to hold your input
...
char s1[SIZE], s2[SIZE], *position; // s1 and s2 declared statically
Second, NEVER NEVER NEVER NEVER NEVER use gets(); it will introduce a point of failure in your program. Use fgets() instead:
if (fgets(s1, sizeof s1, stdin) != NULL)
// process s1
else
// check for EOF or error on read
EDIT
And like everyone else has pointed out, your comparison in the strstr() function needs to be either
*s1 == *s2
or
s1[i] == s2[i]
but first you need to deal with allocating your buffers in main properly.
One of the problems I'm noticing is whenever you do *s1[j]. The asterisk is dereferencing the array, and so is the [] notation.
s[i] really means *(s + i), so you don't have to dereference it again. The way you have it would read **(s + i), and since it's a single pointer you can't do that.
if(*s1[i]==*s2[0])
is such an example where my gcc complains:
error: invalid type argument of ‘unary *’ (have ‘int’)
if s1 is a pointer to char, s1[i] is a char. So you can't dereference it any more (with the *), i.e. s1[i] does not point to anything any more.
Try
if(s1[i]==s2[0])
instead.
You should also change the return value of strstr: you return an integer where you declare to return a pointer to a character. So try returning s1+i instead.
This here:
for(j=i;*s2;j++)
probably does not what you want. You're not advancing the pointer s2 anywhere in the loop, in fact you're just testing whether s2[0] (which is the same as *s2) is zero for each iteration. If s2 isn't the empty string, this loop will never terminate.
#include "stdio.h"
char *strstr(char *str, char *substr)
{
int len = strlen(substr);
char *ref = substr;
while(*str && *ref)
{
if (*str++ == *ref)
{
ref++;
}
if(!*ref)
{
return (str - len);
}
if (len == (ref - substr))
{
ref = substr;
}
}
return NULL;
}
int main(int argc, char *argv[])
{
printf("%s \n", strstr("TEST IS NOT DONE", "IS NOT"));
}
if(*s1[j]!=*s2[j])
*s1 means "the character where s1 is pointing".
s1[j] means "*(s1+j)" or "the character j positions after where s1 is pointing"
You have to use one or the other; not both.
#include <stdio.h>
char* my_strstr(char *s2, char *s1)
{
int i, j;
int flag = 0;
if ((s2 == NULL || s1 == NULL)) return NULL;
for( i = 0; s2[i] != '\0'; i++)
{
if (s2[i] == s1[0])
{
for (j = i; ; j++)
{
if (s1[j-i] == '\0'){ flag = 1; break;}
if (s2[j] == s1[j-i]) continue;
else break;
}
}
if (flag == 1) break;
}
if (flag) return (s2+i);
else return NULL;
}
int main()
{
char s2[] = "This is the statement";
char s1[] = "the";
char *temp;
temp = my_strstr(s2,s1);
printf("%s\n",temp);
return 0;
}

Resources