I can't figure out how to remove the spaces at the beginning of the sentence without using any libraries other than stdio.h and stdlib.h.
#include <stdio.h>
int main()
{
char text[1000], result[1000];
int c = 0, d = 0;
printf("Enter some text\n");
gets(text);
while (text[c] != '\0') { // till the end of the string
if (text[c] == ' ') {
int temp = c + 1;
if (text[temp] != '\0') {
while (text[temp] == ' ' && text[temp] != '\0') {
if (text[temp] == ' ') {
c++;
}
temp++;
}
}
}
result[d] = text[c];
c++;
d++;
}
result[d] = '\0';
printf("Text after removing blanks\n%s\n", result);
return 0;
}
This piece of code removes all the extra spaces of a sentence.
Example:
input: " this is my program."
output: " this is my program."
EXPECTED OUTPUT: "this is my program."
this code leaves only one space where there were more spaces, but I want to remove all spaces at the beginning as well like in the expected output.
#include <stdio.h>
int main()
{
char text[1000], result[1000];
int c = 0, d = 0;
printf("Enter some text\n");
gets(text);
// no space at beginning
while(text[c] ==' ') { c++; }
while(text[c] != '\0'){
result[d++] = text[c++]; //take non-space characters
if(text[c]==' ') { result[d++] = text[c++]; } // take one space between words
while(text[c]==' ') { c++; } // skip other spaces
}
result[d] = '\0';
printf("Text after removing blanks\n%s\n", result);
return 0;
}
I want to remove all spaces at the beginning as well.
After getting the input, begin processing up to the first non-white-space.
// do not use gets()
fgets(text, sizeof text, stdin);
text[strcspn(text, "\n")] = '\0'; //lop off potential \n
char *ptext = text;
while (isspace((unsigned char) *ptext)) {
ptext++;
}
// now use ptext instead of text for rest of code.
This function will process the input array as you need
void remove_white_space(char *source, char *result) {
int i=0,key=0,k=0;
while (source[i]!='\0') {
if(source[i]==' ') {
if (key== 0) {
if(i==0) {
key=1;
++i;
} else {
key=1;
result[k]=source[i];
++k;
++i;
}
} else
++i;
} else {
key=0;
result[k]=source[i];
++k;
++i;
}
}
result[k]='\0';
}
Related
Right now I have a string looking like this:
A sentence
with a newline.
I'm reading the string in via console input like so:
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
And, after reading it in, I remove the whitespace present by doing this in a function and applying to the msg char array:
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
I've tried looping over it and stopping at \n but that leaves an output of "Asentence", as the string terminates as the \n is set to 0.
Whole main:
int main(void) {
char msg[MAX_MSG_LEN+1];
char ch;
int i = 0;
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
msg[i] = '.';
msg[i + 1] = '\0';
remove_white_spaces(msg);
printf("%s\n", msg);
return 0;
}
You can use the isspace function to test for and skip any/all whitespace characters, include the normal space and the newline character(s):
#include <ctype.h> // For definition of "isspace"
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (!isspace((unsigned char)(str[i])))
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
On the reason for casting the argument to isspace to an unsigned char, see this discussion.
Function removing and replacing any chars in the string.
toRemove - chars to remove
addSpace - replace with space
allowMultiple - allow multiple spaces when replacing more adjanced
characters
allowEdges - allow adding spaces at the from and at the end
char *removeChars(char *str, const char *toRemove, const int addSpace, const int allowMultiple, int const allowEdges)
{
char *rd = str, *wr = str;
int replaced = 0;
if(rd)
{
while(*rd)
{
if(strchr(toRemove, *rd))
{
if(addSpace)
{
if(!replaced || allowMultiple)
{
if(wr != str || (wr == str && allowEdges))
{
*wr++ = ' ';
replaced = 1;
}
}
}
}
else
{
*wr++ = *rd;
replaced = 0;
}
rd++;
}
if(allowEdges) *wr = 0;
else
while((wr - 1) > str)
{
if(*(wr - 1) == ' ') {*(wr - 1) = 0; wr--;}
else break;
}
}
return str;
}
int main(void)
{
char str[] = "%%%%%A sentence\n\n\nwith!##$%^a newline.%%%%%%%";
printf("`%s`\n", removeChars(str,"\n!##$%^", 1, 0, 0));
}
Following the suggestion of #MarkBenningfield I did the following and checked for '\n' and just replaced it with a space.
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
if (ch == '\n') {
ch = ' ';
}
}
This program should replace two spaces with an x, using only getchar() and putchar(). My approach was to store the space in a buffer and then print it out. But the program replaces every space with an x. Can someone help me out?
#include <stdio.h>
#define MAX 2
char arr[MAX];
int ret = 0;
char second;
int main()
{
for(int i=0; ; )
{
if ( (ret = getchar())!= EOF)
{
putchar(ret);
}
if(ret==' '&&second==' ')
{
arr[i]=ret;
arr[i]='x';
putchar(arr[i]);
}
}
return 0;
}
When you read a character, first check if it's a space. If not, just print it. If it is read another character, then if the second is a space print an x otherwise print a space and the character you just read.
int c;
while ((c = getchar()) != EOF) {
if (c != ' ') {
putchar(c);
} else {
c = getchar();
if (c == EOF) {
putchar(' ');
} else if (c == ' ') {
putchar('x');
} else {
putchar(' ');
putchar(c);
}
}
}
I have this string: print "Foo cakes are yum"
I need to somehow strip all extra whitespace but leave text between quotes alone. This is what i have so far:
char* clean_strip(char* string)
{
int d = 0, c = 0;
char* newstr;
while(string[c] != '\0'){
if(string[c] == ' '){
int temp = c + 1;
if(string[temp] != '\0'){
while(string[temp] == ' ' && string[temp] != '\0'){
if(string[temp] == ' '){
c++;
}
temp++;
}
}
}
newstr[d] = string[c];
c++;
d++;
}
return newstr;
}
This returns this string: print "Foo cakes are yum"
I need to be able to skip text between thw quotes so i get this: print "Foo cakes are yum".
Here is the same question but for php, i need a c answer: Remove spaces in string, excluding these in specified between specified characters
Please help.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* clean_strip(char* string)
{
int d = 0, c = 0;
char* newstr = malloc(strlen(string)+1);
int quoted = 0;
while(string[c] != '\0'){
if (string[c] == '"') quoted = !quoted;
if(!quoted && string[c] == ' '){
int temp = c + 1;
if(string[temp] != '\0'){
while(string[temp] == ' ' && string[temp] != '\0'){
if(string[temp] == ' '){
c++;
}
temp++;
}
}
}
newstr[d] = string[c];
c++;
d++;
}
newstr[d] = 0;
return newstr;
}
int main(int argc, char *argv[])
{
char *input = "print \"Foo cakes are yum\"";
char *output = clean_strip(input);
printf(output);
free(output);
return 0;
}
This will produce the output:
print "Foo cakes are yum"
It works by looking for the " character. If it's found it toggles the variable quoted. If quoted is true, then the whitespace removal is skipped.
Also, your original function never allocates memory for newstr. I added the newstr = malloc(...) part. It is important to allocate memory for strings before writing to them.
I simplified your logic a little.
int main(void)
{
char string[] = "print \"Foo cakes are yum\"";
int i = 0, j = 1, quoted=0;
if (string[0] == '"')
{
quoted=1;
}
for(i=1; i< strlen(string); i++)
{
if (string[i] == '"')
{
quoted = 1-quoted;
}
string[j] = string[i];
if (string[j-1]==' ' && string[j] ==' ' && !quoted)
{
;
}
else
{
j++;
}
}
string[j]='\0';
printf("%s\n",string);
return 0;
}
I am trying to write program, which take text and seperate it into sentences.
Input:
Hi, my name is John.
Output:
Hi,
my
name
is
John.
Code
int main ()
{
int str[200];
int i = 0;
puts ("Enter text. Do not forget to put dot at the end.");
do {
str[i] = getchar();
i++;
} while (str[i-1] != '.');
printf("\n");
int k, lenght = 0; //lenght -- the lenght of single word
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
printf ("\n");
k = i - lenght;
do {
putchar (str[k]);
k++;
} while (str[k] != ' ');
lenght = 0;
}
lenght++;
}
printf ("\n stop");
return 0;
}
If you try to run or if you can see, there is an error. It does not output last word.
I tried to put there this cycle:
do {
if (str[i] == ' ') {
printf("\n");
k=i-lenght;
do {
putchar(str[k]);
k++;
}while(str[k] != ' ');
lenght=0;
}
lenght++;
i++;
}while(str[i+1] != '.');
But its the same cycle... I also tried to make function:
void word (char *c,int index, int lenght ) {
printf ("\n");
int i = index - lenght;
do {
putchar (c[i]);
i++;
} while (c[i] != ' ');
return;
}
and I called it instead of do-while cycle (in the "if section " of the code):
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
word(str, i, lenght);
lenght = 0;
}
lenght++;
}
What surpriced me was, that the function was "outputting" only the firs Word in sentence. If the first word was "John" it output "John" "ohn" "hn".
So there is not just one question...
How to remake/repaire the cycle/function to output what I want - all of the words in the sentence?
Why it does not work? Well I know the answer - beacouse thy cycle is built to end on character ' ', but not the '.', but when I tried to change it, it output one more random character after dot.
Just please dont blame me for the code, I am just begginer trying to learn something. I know its not a Masterpiece and I can and I will make it shorter before I finish it.
The reason it doesn't print the last word is that, as soon as it reads it and finds the '.', the for-loop terminates so it doesn't process and output that word.
You could change the for-loop condition to look for the terminating '\0' instead, that should fix it.
#include<stdio.h>
int main ()
{
char str[200];
int i = 0;
puts ("Enter text:");
gets(str);
int k, length = 0;
printf("So the words are:\n");
while(str[i]!='\0')
{
if (str[i] == ' ') {
k = i - length;
do {
putchar (str[k]);
k++;
} while (str[k] != ' ');
printf ("\n");
length = (-1);
}
else if (str[i+1] == '\0') {
k = i - length;
do {
putchar (str[k]);
k++;
} while (str[k] != '\0');
length = 0;
}
length++;
i++;
}
return 0;
}
I want to repace multiple spaces in a string by single space, however my following code doesn't work. What's the logical mistake?
#include<stdio.h>
#include<string.h>
main()
{
char input[100];
int i,j,n,z=0;
scanf("%d",&n);
z=n;
for(i=0;i<n;i++)
scanf("%c",&input[i]);
for(i=0;i<n;i++)
{
if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
{
--z;
for(j=i;j<n;j++)
input[j]=input[j+1];
}
}
for(i=0;i<z;i++)
printf("%c",input[i]);
printf("\n");
}
I would do something like this:
void replace_multi_space_with_single_space(char *str)
{
char *dest = str; /* Destination to copy to */
/* While we're not at the end of the string, loop... */
while (*str != '\0')
{
/* Loop while the current character is a space, AND the next
* character is a space
*/
while (*str == ' ' && *(str + 1) == ' ')
str++; /* Just skip to next character */
/* Copy from the "source" string to the "destination" string,
* while advancing to the next character in both
*/
*dest++ = *str++;
}
/* Make sure the string is properly terminated */
*dest = '\0';
}
Of course, the above function requires you to properly terminate the string, which you currently do not.
What the function above does, is basically copy the string over itself. The exception is when there is a space, when multiple spaces are simply discarded.
Since the function modifies the source string, it can not be used on string literals.
The scanf is giving you some problem: it reads the \n you give after inputting the length n. So, you will miss the last character since for loop exits. The already given answers are good enough. But if you want to follow your own logic, try this:
void main()
{
char input[100];
int i = 0,j,n = 0;
while ((input[n] = getchar()) != '\n') {
n++;
}
input[n] = '\0';
while (i < n)
{
if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
{
for(j=i;j<n;j++)
input[j]=input[j+1];
n--;
}
else
{
i++;
}
}
printf("%s\n",input);
printf("\n");
}
if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
case " 1 3" : when i == 0 accses input[i-1] Out-of-Bounds
scanf("%d",&n);
remain newline, (input[0] <-- '\n')
fix to
scanf("%d%*c",&n);
#include <stdio.h>
char* uniq_spc(char* str){
char *from, *to;
int spc=0;
to=from=str;
while(1){
if(spc && *from == ' ' && to[-1] == ' ')
++from;
else {
spc = (*from==' ')? 1 : 0;
*to++ = *from++;
if(!to[-1])break;
}
}
return str;
}
int main(){
char input[]= " abc de f ";
printf("\"%s\"\n", uniq_spc(input));//output:" abc de f "
return 0;
}
Why make it more complicated than it needs to be? You can use strtok to check for single whitespaces and just ignore those. Then you can use strcat to concatenate the string into a full sentence and then you're done.
This is how I did it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char *pch;
char sentence[1000];
char without[1000];
printf("Sentence: ");
fgets(sentence,1000, stdin);
strtok(sentence, "\n"); // remove any newlines
pch = strtok(sentence, " ");
while(pch != NULL) {
strcat(without, pch);
strcat(without, " \0");
pch = strtok(NULL, " ");
}
without[strlen(without)-1] = '\0'; // remove extra whitespace at the end
printf("|%s|\n",without);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void remove_blanks(char* s);
int main()
{
char const s[] = {'1',' ',' ','2',' ',' ','3'};
remove_blanks(s);
printf("%s",s);
return 0;
}
void remove_blanks(char* s){
int i=0, delta=0, cnt=0;
for (i=0;s[i];++i){
if (s[i]==' ') cnt++;
if (cnt>1){
delta+=1;
cnt=0;
}
s[i-delta]=s[i];
if(delta>0) s[i]='\0';
}
}
You cant try this simple code:
#include <stdio.h>
#define IN 1
#define OUT 0
int main() {
int c, spaces, state;
spaces = 0;
state = OUT;
while ((c = getchar()) != EOF) {
if ( c == ' ') {
++spaces;
state = OUT;
}
else if (state == OUT) {
state = IN;
spaces = 0;
}
if (c == ' ' && spaces > 1 && state == OUT)
c = 0;
putchar(c);
}
return 0;
}
You have to fix the following for loop. the limit of your for loop should be z and not n
for(j=i;j<n;j++)
input[j]=input[j+1];
by
for(j=i;j<z;j++)
input[j]=input[j+1];
BTW: the fist charachter get by your scanf() (which read charachters) is newline (\n). this newline come from the first scanf() of decimal(%d)
#include<stdio.h>
#include<string.h>
int main(void)
{
char input[1000];
int i=0;
gets(input);
for(i=0;input[i]!='\0';i++)
{
if(input[i]!=' ' || input[i+1]!=' ')
printf("%c",input[i]);
}
return 0;
}