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;
}
Related
I'm learning C now
I need to make a program that remove char that I'll input from string. I've seen an algorithm and I write this code
#define MAX_LEN 200
int main()
{
char str[MAX_LEN];
char rem;
int i = 0;
printf("Enter the setence:");
gets(str);
printf("\nEnter the char to remove");
rem = getchar();
char* pDest = str;
char* pS= str;
printf("sent:\n%s", str);
while (str[i]!='\0'){
if (*pDest != rem) {
*pDest = *pS;
pDest++;
pS++;
}
else if (*pDest == rem) {
pS++;
}
i++;
}
*pDest = '\0';
while (str[i] != '\0') {
printf("number%d", i);
putchar(str[i]);
printf("\n");
i++;
}
}
But it returns nothing, like the value str gets, i think \0 and retuns nothing.
May you help me to find the problem?
Use functions!!
If dest is NULL then this function will modify the string str otherwise, it will place the string with removed ch in dest.
It returns reference to the string with removed character.
char *removeChar(char *dest, char *str, const char ch)
{
char *head = dest ? dest : str, *tail = str;
if(str)
{
while(*tail)
{
if(*tail == ch) tail++;
else *head++ = *tail++;
}
*head = 0;
}
return dest ? dest : str;
}
int main(void)
{
char str[] = "ssHeslsslsos sWossrlssd!ss";
printf("Removal of 's' : `%s`\n", removeChar(NULL, str, 's'));
}
It would be easier to use array style indexing to go through the string. For example use str[i] = str[i + 1] instead of *pstr = *other_pstr. I leave this incomplete method, since this looks like homework.
int main()
{
char str[] = "0123456789";
char ch = '3';
for (int i = 0, len = strlen(str); i < len; i++)
if (str[i] == ch)
{
for (int k = i; k < len; k++)
{
//Todo: shift the characters to left
//Hint, it's one line
}
len--;
}
printf("%s\n", str);
return 0;
}
I just added new char array char dest[MAX_LEN] that store string with deleted symbols:
#define MAX_LEN 200
int main()
{
char str[MAX_LEN];
char rem;
int i = 0;
printf("Enter the setence:");
gets(str);
printf("\nEnter the char to remove");
rem = getchar();
char dest[MAX_LEN] = "\0";
char* pDest = dest;
char* pS = str;
printf("sent:\n%s", str);
while (str[i]!='\0')
{
if (*pS != rem)
{
*pDest = *pS;
pDest++;
pS++;
}
else if (*pS == rem)
{
pS++;
}
i++;
}
i = 0;
printf("\nres:\n %s \n", dest);
while (dest[i] != '\0') {
printf("number%d", i);
putchar(dest[i]);
printf("\n");
i++;
}
}
I have program to remove the similar words from string but this program only removing at once word not a repeating words.
For example input:
sabunkerasmaskera kera
and should an output:
sabunmas
This my code:
#include <stdio.h>
#include <string.h>
void remove(char x[100], char y[100][100], char words[100]) {
int i = 0, j = 0, k = 0;
for (i = 0; x[i] != '\0'; i++) {
if (x[i] == ' ') {
y[k][j] = '\0';
k++;
j = 0;
} else {
y[k][j] = x[i];
j++;
}
}
y[k][j] = '\0';
j = 0;
for (i = 0; i < k + 1; i++) {
if (strcmp(y[i], kata) == 0) {
y[i][j] = '\0';
}
}
j = 0;
for (i = 0; i < k + 1; i++) {
if (y[i][j] == '\0')
continue;
else
printf("%s ", y[i]);
}
printf ("\n");
}
int main() {
char x[100], y[100][100], kata[100];
printf ("Enter word:\n");
gets(x);
printf("Enter word to remove:\n");
gets(words);
remove(x, y, words);
return 0;
}
My program output its:
sabunkerasmaskerara
and that should not be the case. Maybe I need your opinion to fixed this program and also I need help to make it better.
Your solution does not work because it uses strcmp to compare the string portions, which only works if the substring is at the end of the string, as this makes it null-terminated.
You should instead use strstr to locate the matches and use memmove to shift the string contents.
There are other issues in your code:
do not use gets()
y is unnecessary for this task.
words is not defined
Here is a modified version:
#include <stdio.h>
#include <string.h>
char *remove_all(char *str, const char *word) {
size_t len = strlen(word);
if (len != 0) {
char *p = str;
while ((p = strstr(p, word)) != NULL) {
memmove(p, p + len, strlen(p + len) + 1);
}
}
return str;
}
int main() {
char str[100], word[100];
printf ("Enter string:\n");
if (!fgets(str, sizeof str, stdin))
return 1;
printf("Enter word to remove:\n");
if (!fgets(word, sizeof word, stdin))
return 1;
word[strcspn(word, "\n")] = '\0'; // strip the trailing newline if any
remove_all(str, word);
fputs(str, stdout);
return 0;
}
So I am kinda new to coding, but what I want to do is write a string, write one character I wish not to be in the string if it occurs. I've tried using removedChar = getchar() instead of fgets(removedChar, 2, stdin); but then I can't do the != in the if statement.
I would really appreciate your help.
int main() {
char str[20], removedChar[2];
int i, n, j;
printf("ENTER A STRING:");
fgets(str, 20, stdin);
printf("ENTER WHAT CHAR YOU WISH TO REMOVE: ");
fgets(removedChar, 2, stdin);
n = strlen(str);
for (i = 0, j = 0; i < n; i++) {
if (strcmp(str, removedChar) == 0) {
str[j] = str[i];
j++;
}
if (str[i] == ' ') {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
printf("string after removing character = %s", str);
system("pause");
return 0;
}
Firstly this line:
if (strcmp(str, removedChar) == 0)
is comparing if two strings are identical. Please see strcmp.
You need to instead compare character against characters, instead of equality of string against string.
Having said this, you can now just simply loop over the string, and use != to rule out matching characters, and update the string accordingly with a counter.
Additionally, it is always safe to check the return value of fgets, and also check that you havn't exceeded the buffer length.
This is the code that uses these ideas:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRSIZE 20
int
main(int argc, const char *argv[]) {
char str[STRSIZE];
int i, j, removedchar;
size_t slen;
printf("Enter a string: ");
if (fgets(str, STRSIZE, stdin) == NULL) {
printf("Error reading string\n");
return 1;
}
slen = strlen(str);
if (slen > 0) {
if (str[slen-1] == '\n') {
str[slen-1] = '\0';
} else {
printf("Error: Exceeded Buffer length of %d.\n", STRSIZE);
return 1;
}
}
if(!*str) {
printf("Error: No string entered.\n");
return 1;
}
printf("Enter what character you wish to remove: ");
removedchar = getchar();
if (removedchar == '\n') {
removedchar = ' ';
printf("No character was entered. Spaces will be removed if found\n");
}
j = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] != removedchar) {
str[j++] = str[i];
}
}
str[j] = '\0';
printf("Changed String = %s\n", str);
return 0;
}
You should use str[i] != removedChar[0] instead of using strcmp() which compares the full strings.
Also note that you should strip the newline character from the string read by fgets().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char str[80], removedChar[80];
int i, n, j;
printf("ENTER A STRING: ");
if (!fgets(str, sizeof str, stdin))
return 1;
str[strcspn(str, "\n")] = '\0'; // strip the newline character if present
printf("ENTER WHAT CHAR YOU WISH TO REMOVE: ");
if (!fgets(removedChar, sizeof removedChar, stdin))
return 1;
for (i = 0, j = 0; str[i] != '\0'; i++) {
if (str[i] != removedChar[0]) {
str[j] = str[i];
j++;
}
}
str[j] = '\0';
printf("string after removing character = %s\n", str);
system("pause");
return 0;
}
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/
A friend of mine needed help counting the occurrences of a substring in a string, and I came up with the following code. Does anyone know a better method to do this?
#include "stdio.h"
#include "string.h"
int main(int argc, char *argv[])
{
char str1[50], str2[50];
int i, j, l1, l2, match, count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
l1 = strlen(str1);
l2 = strlen(str2);
count = 0;
for(i = 0; i < l1; i++)
{
match = 0;
for(j = 0; j < l2; j++)
{
if(str1[i + j] == str2[j])
{
match++;
}
}
if(match == l2)
{
count++;
}
}
printf("Substrings: %d\n", count);
}
how about this: (using the strstr function, reference here)
int count = 0;
char str1[50], str2[50];
char* tmp = str1;
int count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
while(*tmp != '\0' && (tmp = strstr(tmp, str2))) {
++count;
++tmp;
}
Please do not use or encourage the use of gets. Beyond the fact that it will introduce a point of failure in your code, it has been deprecated as of C99 and will be gone completely from C1X.
As others have said, strstr is your friend here:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[50], s2[50];
char *p;
size_t count = 0;
size_t len1;
printf("Gimme a string: ");
fflush(stdout);
fgets(s1, sizeof s1, stdin);
p = strchr(s1, '\n'); // get rid of the trailing newline
if (p)
*p = 0;
printf("Gimme another string: ");
fflush(stdout);
fgets(s2, sizeof s2, stdin);
p = strchr(s2, '\n'); // get rid of the trailing newline
if (p)
*p = 0;
p = s2;
len1 = strlen(s1);
while ((p = strstr(p, s1)) != NULL && p != s1)
{
count++;
p += len1;
}
printf("Found %lu occurrences of %s in %s\n", count, s1, s2);
return 0;
}
You might want to take a look at the strstr function (if you're not already familiar with it).
int main()
{
char *str = "This is demo";
char *sub = "is";
int i,j,count;
i=j=count=0;
while(str[i]!='\0')
{
if (str[i] == sub[j] && str[i+1] == sub[j+1])
{
count++;
}
i++;
}
cout<<count;
return 0;
}
Above code works but this is static.
You can use QString in QT library
QString t = "yourstring";
t.count("yoursubstring");