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.
Related
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;
}
}
}
Im trying to make the program remove a character from a string that the user is putting in but i get an error inside the loop. (side question: is adding a character inside the string the "same" code with some small changes?)
PS New to programming...
Is this what you are trying to achieve?
Changes:
getchar() and fgets() to scanf()
added strlen() to get length of string
added lenght of input string to printf
added zero init of strings
Note: After each input with scanf() you have to press enter.
int main()
{
char str[100] = { 0 };
char ch[5] = { 0 };
int k, j;
printf("Write text:\n");
scanf("%s", str);
printf("Input was: %s\nLength: %d\n", str, strlen(str));
printf("Write a character that should be removed\n");
scanf("%s", ch);
for (k = 0, j = 0; k < strlen(str); k++)
{
if (str[k] != ch[0]) {
str[j] = str[k];
j++;
}
}
str[j] = '\0';
printf("String after removing a character: %s", str);
}
Problems with your code:
str[k] != ch would be a valid test if ch were indeed a character and not an array of characters of length 5. This is going to compare the character value of str[k] with the address &ch[0].
k < str would be a valid comparison if k was a char * pointer that was initialized at &str[0], not an int loop index starting at 0.
Corrected code:
int main(void)
{
char str[100];
char ch[5];
int k, j;
printf("Write text:\n");
//getchar();
fgets(str, 100, stdin);
printf("Input was: %s\n", str);
printf("Write a character that should be removed\n");
//getchar();
fgets(ch, 5, stdin);
for (k = 0, j = 0; k < strlen(str); k++)
{
if (str[k] != ch[0])
{
str[j] = str[k];
j++;
}
}
str[j] = '\0';
printf("String after removing a character = %s", str);
return 0;
}
Here you have two implementations. Both remove all occurrences of the char ch from the string str
First algorithm is much faster. The second slower but easy to understand
#include <stdio.h>
#include <string.h>
char *removechar(char *str, int ch)
{
char *cptr = str, *readptr = str;
while(*readptr)
{
if(*readptr == ch)
{
readptr++;
}
else
{
*cptr++ = *readptr++;
}
}
*cptr = 0;
return str;
}
char *removechar(char *str, int ch)
{
char *cpos = str;
while((cpos = strchr(cpos, ch)))
{
strcpy(cpos, cpos + 1);
}
return str;
}
int main()
{
char s[] = "Hello World";
printf("%s\n", removechar(s, 'd'));
printf("%s\n", removechar(s, 'l'));
return 0;
}
Is this what you want to achieve?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[100],c;
printf("Write text:\n");
fgets(str,100,stdin);
printf("Input was: %s\n", str);
printf("Write a character that should be removed\n");
c=getchar();
for(int k=0;k<strlen(str);k++){
if(str[k]==c){
for(int j=k;j<strlen(str);j++){
str[j]=str[j+1];
}
}
}
printf("String after removing a character = %s", str);
return 0;
}
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 tried to manually count the number of characters in my string including any blank spaces. I coded this:
#include <stdio.h>
#include <stdlib.h>
void Unos(char* string, int duzina)
{
int i=0;
char c;
do {
c=getchar();
string[i]=c;
i++;
} while(c != '\n' && i<duzina);
}
int brojznak(char* str)
{
int i=0,br=0;
while(*str++ != '\0')
{
br++;
}
return br;
}
int main()
{
char recenica[100];
printf("Unesite recenicu\n");
Unos(recenica,100);
int i=0;
printf("%d",brojznak(recenica));
return 0;
}
This code doesn't work correctly, but I think it should. On the other hand, if we change condition:
int brojznak(char* str)
{
int i=0,br=0;
while(*str++ != '\0')
{
br++;
}
return br;
}
It again sometimes prints some random characters, but counts it accurately. Can anyone tell me what is wrong in this code?
String termination missing in Unos().
while(*str++ != '\0') in brojznak() does not know when to stop.
void Unos(char* string, int duzina) {
int i=0;
char c;
do {
c = getchar();
string[i] = c;
i++;
} while(c != '\n' && (i + 1) <duzina); // Insure enough room
string[i]='\0'; // add this
}
Some other refinements:
void Unos2(char* string, size_t duzina) {
size_t i = 0;
while ((i+1) < duzina) { Only attempt to read if space allows it.
int c = getchar(); // Use int to distinguish EOF from characters
if (c == EOF) break;
string[i] = c;
i++;
if (c == '\n') break;
}
string[i] = '\0'; // add this
}
try this
for(i=0; getchar()!='\n'; ++i)
;
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/