I'm learning C recently and I didn't learn about pointers so still not allowed to use it.
Note: i'm not allowed to use it or any function from string.h library.
I wrote a function that removes the "\n" from a string.
when I run my program appears to me:
main.c:20:14: warning: comparison between pointer and integer
main.c:80:39: warning: format not a string literal and no format arguments [-Wformat-security]
This is my function:
#include <stdio.h>
#define STRING_SIZE 100
void replace(char str[]){
int i=0;
while(str[i]!='\0'){
if(str[i]=="\n"){
str[i]='\0';
}
}
}
int my_strlen(char s[]) {
int i = 0;
while (s[i] != '\0') {
i++;
}
return i;
}
int remover(char s1[], char s2[], char s3[]) //removes the sustring s2 from string s1 and saved it to s3
{
int i = 0, j, t = 0, found;
while (s1[i])
{
found = 1;//Initilize found to true
for (j = 0; s2[j] != 0; j++) {
if (s1[i + j] != s2[j])
found = 0;//Set not found
}
if (found == 0) {
s3[t] = s1[i];// if not found add char to s3.
t++;
}
else {
i = i + my_strlen(s2) - 1;//if found skip
}
i++;
}
s3[t] = 0;
if (my_strlen(s1) > my_strlen(s3)) {
return 1;
}
return 0;
}
int main() {
char result_string[STRING_SIZE+1], MainString[STRING_SIZE+1], PatternString[STRING_SIZE+1];
printf("Please enter the main string..\n");
fgets(MainString, STRING_SIZE + 1, stdin);
replace(MainString);
printf("Please enter the pattern string to find..\n");
fgets(PatternString, STRING_SIZE + 1, stdin);
replace(PatternString);
int is_stripped = remover(MainString, PatternString, result_string);
printf("> ");
printf(is_stripped ? result_string : "Cannot find the pattern in the string!");
return 0;
}
what's the problem?
You have a lot of problems:
Your function returns a char, which is a single character.
A C-style string has to have a terminating zero byte. You don't put one on helper. So even if you could return it properly, the code that got it would have no way to know how long the string was.
You allocate helper on the stack in replace, so helper stops existing when you return. So where will the returned string be stored?
Just remove the '\n' from the string, in place, modifying the original string.
For instance:
void remove_newline(char str[])
{
int i;
for(i=0; str[i] != 0; ++i)
{
if (str[i] == '\n')
{
str[i] = 0;
break;
}
}
}
Related
This is from an exercise in Chapter 9 of Programming in C 4th Edition. The programme is to read in characters into a string and extract a portion of the string into a sub-string by specifying a start position and number of characters.
The programme compiles and runs well except when the zeroth position of the source is stated as the start. Nothing is then displayed.
This is my code.
/* Programme to extract a portion from a string using function
sub-string (source, start, count, result) ex9.4.c
ALGORITHM
Get text input into a char array (declare to be fixed size);
Determine length of source string;
Prepare result array to be dynamic length using desired count + 1;
Copy from source array into result array
*/
#include <stdio.h>
#include <stdbool.h>
#define MAX 501
void read_Line (char buffer[]);
int string_Length (char string[]);
void sub_String (char source[], int start, int count, char result[]);
int main(void)
{
char strSource[MAX];
bool end_Of_Text = false;
int strCount = 0;
printf("This is a programme to extract a sub-string from a source string.\n");
printf("\nType in your text (up to 500 characters).\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(strSource);
if (strSource[0] == '\0')
{
end_Of_Text = true;
}
else
{
strCount += string_Length(strSource);
}
}
// Declare variables to store sub-string parameters
int subStart, subCount;
char subResult[MAX];
printf("Enter start position for sub-string: ");
scanf(" %i", &subStart);
getchar();
printf("Enter number of characters to extract: ");
scanf(" %i", &subCount);
getchar();
// Call sub-string function
sub_String(strSource, subStart, subCount, subResult);
return 0;
}
// Function to get text input
void read_Line (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
}
while (character != '\n');
buffer[i - 1] = '\0';
}
// Function to count determine the length of a string
int string_Length (char string[])
{
int len = 0;
while (string[len] != '\0')
{
++len;
}
return len;
}
// Function to extract substring
void sub_String (char source[], int start, int count, char result[])
{
int i, j, k;
k = start + count;
for (i = start, j = 0; i < k || i == '\0'; ++i, ++j)
{
result[j] = source[i];
}
result[k] = '\0';
printf("%s\n", result);
}
I am using Code::Blocks on Linux Mint.
Being someone that just started learning programming recently with CS50 and 'Programming in C' books, I did not know how to setup the debugger in Code::Blocks. But thanks to the push by #paulsm4, I managed to get the debugger working. Using the watches window of the debugger, I could see that the while loop in the main function was overwriting the first character in the source array with a null character. The fix was to add a break statement. Thanks to #WhozCraig and #Pascal Getreuer for pointing out other errors that I had missed. This is the corrected code now:
/* Programme to extract a portion from a string using function
sub-string (source, start, count, result) ex9.4.c
ALGORITHM
Get text input into a char array (declare to be fixed size);
Determine length of source string;
Prepare result array to be dynamic length using desired count + 1;
Copy from source array into result array
*/
#include <stdio.h>
#include <stdbool.h>
#define MAX 501
void read_Line (char buffer[]);
int string_Length (char string[]);
void sub_String (char source[], int start, int count, char result[]);
int main(void)
{
char strSource[MAX];
bool end_Of_Text = false;
int strCount = 0;
printf("This is a programme to extract a sub-string from a source string.\n");
printf("\nType in your text (up to 500 characters).\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(strSource);
if (strSource[0] == '\0')
{
end_Of_Text = true;
}
else
{
strCount += string_Length(strSource);
}
break;
}
// Declare variables to store sub-string parameters
int subStart, subCount;
char subResult[MAX];
printf("Enter start position for sub-string: ");
scanf(" %i", &subStart);
getchar();
printf("Enter number of characters to extract: ");
scanf(" %i", &subCount);
getchar();
// Call sub-string function
sub_String(strSource, subStart, subCount, subResult);
return 0;
}
// Function to get text input
void read_Line (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
}
while (character != '\n');
buffer[i - 1] = '\0';
}
// Function to count determine the length of a string
int string_Length (char string[])
{
int len = 0;
while (string[len] != '\0')
{
++len;
}
return len;
}
// Function to extract substring
void sub_String (char source[], int start, int count, char result[])
{
int i, j, k;
k = start + count;
// Source[i] == '\0' is used in case count exceeds source string length
for (i = start, j = 0; i < k || source[i] == '\0'; ++i, ++j)
{
result[j] = source[i];
}
result[j] = '\0';
printf("%s\n", result);
}
My code is supposed to compare 2 strings and returns the common characters in alphabetical order. If there are no common chars, it will return a null string.
However the program is not running.
Code
void strIntersect(char *str1, char *str2, char *str3)
{
int i,j, k;
i = 0;
j = 0;
k = 0;
while(str1[i]!='\0' || str2[j]!='\0')
{
if(strcmp(str1[i],str2[j])>0)
{
str3[k] = str1[i];
k++;
}
else if (strcmp(str2[j],str1[i])>0)
{
str3[k] = str2[j];
k++;
}
i++;
j++;
}
}
Example
Input string 1:abcde
Input string 2:dec
Output: cde
How do I get it to work?
There are quite a few problems with your code
strcmp is not needed for a simple char comparison
Is the 3rd char string allocated by the caller?
Your approach won't work if source strings are either of different sizes or are not alphabetical.
My solution assumes that input is ASCII, and is efficient (used a simple char array with indexes denoting ASCII value of the character).
If a character is found in str1, the char map will have a 1, if it is common, it will have a 2, otherwise, it will have a 0.
void strIntersect(char *str1, char *str2, char *str3)
{
int i=0, j=0, k=0;
char commonCharsMap[128] = { 0 };
while(str1[i] != '\0')
{
commonCharsMap[str1[i++]] = 1;
}
while(str2[j] != '\0')
{
if(commonCharsMap[str2[j]] == 1)
{
commonCharsMap[str2[j++]] = 2;
}
}
for(i=0; i<128; i++)
{
if(commonCharsMap[i] == 2)
{
str3[k++] = i;
}
}
str3[k++] = '\0';
}
int main()
{
char str1[] = "abcde";
char str2[] = "dce";
char str3[30];
strIntersect(str1, str2, str3);
printf("Common chars: %s\n", str3);
return 0;
}
A option is to iterate over the complete second string for each character in the first string
int i = 0;
int k = 0;
while(str1[i] != '\0') {
int j = 0;
while(str2[j] != '\0') {
if (str1[i] == str2[j]) {
str3[k] = str1[i];
k++;
}
j++;
}
i++;
}
I replaced the strcmp because you are comparing single characters not a string
Your if case and Else if case are identical and you are just comparing elements according to your Index. i.e you are comparing first element with first, second with second and so on. This won't provide you solution. I suggest use two for loops. I will provide you code later if you want
I'm trying to remove consecutive repeated characters from a given string.
Example:
bssdffFdcrrrtttii ***#
output is supposed to be:
bsdfFdcrti *#
This code doesn't work and only prints the first char (b), I want to learn about my mistake.
when I'm doing a printf test, it works but not for spaces.
I think the problem might be with the new char array.
void Ex6() {
char* string[80];
scanf("%s", &string);
puts(removeDup(string));
}
char* removeDup(char *string) {
int i, c = 0;
char* newString[80];
for (i = 0; i < strlen(string); i++) {
if (string[i] != string[i + 1]) {
newString[c++] = string[i];
}
}
return newString;
}
There are several problems with your program:
The declaration of newString should be char newString[80], i.e., an array of characters and not an array of pointers-to-characters, and likewise for the declaration in Ex6.
The call to scanf should then be scanf("%s", string), since string is already the address of an array of characters, but...
Use fgets to read a string from the user to ensure that you read whitespace, if it's important, and that the buffer is not exceeded.
newString is allocated on the stack and so should not be returned to the caller. It is better to do a char *newString = strdup(string), or, slightly less sloppy, char *newString = malloc(strlen(string)+1), which will call malloc for a block of memory sufficient to hold the original string, and thus the version without duplicates -- the comments rightly point out that this could be optimized. In principle, the caller, i.e., Ex6, must free the returned pointer to avoid a memory leak but it hardly matters in such a short program.
The result needs a null terminator: newString[c] = '\0'.
Otherwise, the removeDup function seems to work correctly.
So, putting all of that together:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* removeDup(const char *string)
{
size_t i, c = 0;
size_t string_len = strlen(string);
char *newString = malloc(string_len + 1);
for (i = 0; i < string_len; i++) {
if (string[i] != string[i + 1]) {
newString[c++] = string[i];
}
}
newString[c] = '\0';
return newString;
}
#define MAX_STRING_LEN 80
void Ex6() {
char string[MAX_STRING_LEN];
char* result;
if (fgets(string, MAX_STRING_LEN, stdin) != NULL) {
result = removeDup(string);
printf("%s", result);
free(result);
}
}
Finally, I agree with #tadman's comment. Since the input string must anyway be traversed to calculate the length, we may as well optimize the size of the result string:
char* removeDup(const char *string)
{
size_t i, c = 0;
char *newString;
for (i = 0; string[i] != '\0'; i++)
c += (string[i] != string[i + 1]);
newString = malloc(c + 1);
for (i = c = 0; string[i] != '\0'; i++) {
if (string[i] != string[i + 1]) {
newString[c++] = string[i];
}
}
newString[c] = '\0';
return newString;
}
There are quite a few issues in your program. It wouldn't even compile let alone run. Also, the most problematic issue is that you are returning a pointer to a local variable from a function that ceases its scope upon completion. A simplified version of your program is as follows:
void Ex6()
{
char string[80];
scanf("%s", string);
int i, c = 0;
char newString[80];
for (i = 0; i < strlen(string); i++) {
if (string[i] != string[i + 1]) {
newString[c++] = string[i];
}
}
newString[c] = '\0';
puts(newString);
}
You can do it with O(n) time and O(1) space, by modifying existing string:
#include <stdio.h>
char* removeDup(char* input) {
char* newTail = input, *oldTail = input;
while (*oldTail) {
if (*newTail == *oldTail) {
++oldTail;
} else {
*++newTail = *oldTail++;
}
}
return newTail;
}
int main() {
char string[] = "bssdffFdcrrrtttii ***#";
char* newEnd = removeDup(string);
char* tmp = string;
while (tmp != newEnd) {
printf("%c", *tmp++);
}
//Print the last char if string had any duplicates
if(*tmp) {
printf("%c", *tmp++);
}
return 0;
}
I declared an empty string:
char str[MAX_LEN] = "\0"; //empty String
and then
void InitString(char *str,int maxlenght)
{
char input = 0;
int counter = 0,i;
for(i = 0;i<(maxlenght);i++)
{
*(str+i) = '\0';
}
getchar();
printf("\nEnter new string of max %d chars: ",maxlenght);
while (input != '\r' && counter < (maxlenght-1))
{
input = getche();
*(str+counter) = input;
counter++;
}
}
void PrintString(char *str)
{
int i = 0;
printf("\nThe String Created is : ");
puts(str);
while(*(str+i) != '\0')
{
printf("%c", *(str+i));
i++;
}
}
I have no idea why this code behaves differently since the code is identical in logic to the upper one.
int CountWords(char *str)
{
int i = 0;
char ch;
while(*(str+i) != '\0')
{
printf("%d", *(str+i));
ch = *(str+i);
printf("%c",ch);
numNumber++;
i++;
}
return i;
}
There is no output for the lower code block even though the test condition is the same.
Your problem is that you are using puts(). This states
The C library function int puts(const char *str) writes a string to stdout up to but not including the null character. A newline character is appended to the output.
Thus, if puts() uses strlen() then your '\0' is replaced by a '\n' and that is why your while loop doesn't work.
I wrote the following function for removing duplicate characters from a string..For ex: if
str = "heeello;
removeDuplicate(str)
will return helo...But it shows some error on runtime .I have added some printf() statements for debugging...Can anyone tell me what the problem is ?
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
printf("\nstr is %s",str);
while((ch = str[i++] )!= '\0')
{
j = i;
printf("\n----ch = %c----",ch);
while(str[j] != '\0')
{
printf("\n--------Checking whether %c = %c \n",str[j],ch);
if(ch == str[j])
{
printf("\n------------Yes");
while(str[j]!='\0')
{
printf("\nRemoving %c %d -- \n",str[j]);
str[j] = str[++j];
--i;
}
break;
}
printf("\n------------No");
//printf("\njj");
j++;
}
}
return str;
}
You are passing a string literal, which you are not allowed to modify to this function, instead you should do:
char myStr[] = "heee";
removeDuplicate(myStr);
Also, please note that in the following lines your have to specifiers inside the printf (%c %d), but you pass only one argument (str[j]):
printf("\nRemoving %c %d -- \n",str[j]);
This may cause all sorts of bad things...
You should correct your code as follows:
In first while loop: j = i+1;
In third while loop: i--; // is not required
Remove that unwanted specifier form printf("Removing %d %d:",str[j])
Doing incorrectly :
str[j] = str[++j] // you are increasing j before assigning
str[j] = str[j++] // correct way to do.But it is compiler dependent i guess
Better to use:
t = j;
str[t] = str[++j];
I don't think this function does what you want. The remove loop is really fishy.. you decrement i which looks wrong.. and you increment j which is probably also wrong:
while(str[j]!='\0')
{
printf("\nRemoving %c %d -- \n",str[j]);
str[j] = str[++j]; // now the new character is at location j, but since
// you incremented j you can't access it anymore
--i; // why is i dependent on the remove stuff?
}
I would go for a simpler approach. Create a large bool array. Loop through your string and store whether you already encountered the current character or not. If not, print it.
Check the following code :
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
int repIndex=0;
int temp=0;
printf("\nstr is %s",str);
while((ch = str[i++] )!= '\0')
{
j = i;
printf("\n----ch = %c----",ch);
while(str[j] != '\0')
{
printf("\n--------Checking whether %c = %c \n",str[j],ch);
repIndex = j;
if(ch == str[repIndex])
{
printf("\n------------Yes");
while(str[repIndex]!='\0')
{
printf("\nRemoving %c %d \n",str[j]);
temp = repIndex;
str[temp] = str[++repIndex];
}
} else { j++; }
}
}
return str;
}
int main ( int argc, char ** argv)
{
char myStr[]="asdfhelllasdfloofdoeohz";
printf ("OUtput is : %s \n", removeDuplicate(myStr) );
}
//removing the redundant characters in a string
#include<stdio.h>
int main()
{
int i=0,j,arr[26]={},temp; //array for hashing
char s[10],arr1[10],*p; //array 4 storing d output string
printf("Enter the string\n");
scanf("%s",s);
p=s;
while(*p!='\0')
{
temp=((*p)>92)?(*p)-'a':(*p)-'A'; //asuming lowr and upr letters are same
if(arr[temp]==0) //if it is not hashed ie if that char is not repeated
{
arr1[i]=temp+'a'; //return the string in lowecase
arr[temp]=1; //storing value so that this character sd not be placed again
i++;
}
p++; //else ignore the alphabet
}
for(j=0;j<i;j++)
{
printf("%c",arr1[j]); //print the string stored in arr1
}
return 0;
}
I have corrected the code as follows
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
while((ch = str[i++] )!= '\0')
{
j = i;
while(str[j] != '\0')
{
if(ch == str[j])
{
while(str[j]!='\0')
str[j] = str[++j];
i--;
break;
}
j++;
}
}
return str;
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
char *str;
int count=0;
cout<<"enter the string which have repetative characters"<<endl;
cin>>str;
char *str2;
int m=0;
for(int i=0;i<=strlen(str);i++)
{
char ch=str[i];
if(i==0)
{
str2[m]=str[i];
m++;
}
for(int j=0;j<=strlen(str2);j++)
{
if(ch==str2[j])
count++;
}
if(count==0)
{
str2[m]=str[i];
m++;
}
count=0;
if(i==strlen(str))
str2[m]='\0';
}
puts(str2);
getch();
}
O(n) complexity
char *removeDuplicates(char *str){
int hash[256] = {0};
int currentIndex = 0;
int lastUniqueIndex = 0;
while(*(str+currentIndex)){
char temp = *(str+currentIndex);
if(0 == hash[temp]){
hash[temp] = 1;
*(str+lastUniqueIndex) = temp;
lastUniqueIndex++;
}
currentIndex++;
}
*(str+lastUniqueIndex) = '\0';
return str;
}
Refer: http://www.geeksforgeeks.org/remove-all-duplicates-from-the-input-string/