I take as input a string with spaces in it and replace the spaces with the NULL character '\0'. When I print the string now, I expect only the part till the first NULL character which was the first space earlier but I am getting the original string.
Here is the code-
#include<stdio.h>
int main(){
char a[1000];
int length, i = 0;
length = 0;
scanf("%[^\n]s", a);
while(a[i]!='\0')
i++;
length = i;
printf("Length:%d\n", length);
printf("Before:%s\n", a);
for(i=0;i<length;i++){
if(a[i] == " ")
a[i] = '\0';
}
printf("After:%s\n", a);
return 0;
}
What is wrong in this?
Your code is wrong.
for(i=0;i<length;i++){
if(a[i] == " ")
a[i] = '\0';
}
The comparison is trying to compare a character with a pointer (denoted by " " ->This becomes a pointer to a string of characters. In this case the string is only having a space.)
This can be fixed by the following replacement
for(i=0;i<length;i++){
if(a[i] == ' ')
a[i] = '\0';
}
Or better to do it in this manner, since you can have other whitespace too like tab, apart from space.
(Please include ctype.h also)
for(i=0;i<length;i++){
if(isspace(a[i]))
a[i] = '\0';
}
Related
In C apparently strings are stored like an array with a null value or '\0' at the end. I wish to iterate over the string in a for loop and I need it to stop at '\0', not including it. I've tried many conditions for the if else and it all don't seem to work.
for example:
char patternInput[TEXTSIZE];
for(int i = 0; i<strlen(patternInput);i++)
{
if(patternInput[i]==NULL)
{
printf("\nlast character");
break;
}
else
{
printf("\n%c",patternInput[i]);
}
}
I've tried if(patternInput[i]==NULL), if(patternInput[i]==NUL),if(!patternInput[i]),if(patternInput[i]=='\0') and none of them seems to work.
If you're scanning the characters yourself, you can avoid the (redundant and somewhat expensive) strlen() call entirely, and instead use the value of patternInput[i] in the continuation-test of your for-loop:
char patternInput[TEXTSIZE] = "testing!";
for(int i = 0; patternInput[i] != '\0'; i++)
{
printf("\n%c",patternInput[i]);
}
printf("\nlast character\n");
Consider this code. This code prints 'Null character found' with position of the character. Notice the 'less than or equal to' in i<=strlen(str) in the loop invariant.
The last character at the length strlen + 1 is the '\0' character.
int i = 0;
char str[] = "Hello";
for(int i=0; i<=strlen(str); i++)
{
if(str[i]=='\0')
printf("Null character found at position %d", i);
}
I'm just starting to code and I need help figuring out why this loop counts spaces within a string.
To my understanding, this code should tell the computer to not count a space "/0" and increase count if the loop goes through the string and it's any other character.
int main(void)
{
string t = get_string("Copy & Past Text\n");
int lettercount = 0;
for (int i = 0; t[i] != '\0'; i++)
{
lettercount++;
}
printf("%i", lettercount);
printf("/n");
}
\0 represents the null character, not a space. It is found at the end of strings to indicate their end. To only check for spaces, add a conditional statement inside the loop.
int main(void)
{
string t = get_string("Copy & Past Text\n");
int lettercount = 0;
for (int i = 0; t[i] != '\0'; i++)
{
if (t[i] != ' ')
lettercount++;
}
printf("%i", lettercount);
printf("\n");
}
Space is considered a character, your code goes through the string (an array of characters) and counts the characters until it reaches the string-terminating character which is '\0'.
Edit: set an if condition in the loop if(t[i] != ' ') and you wouldn't count the spaces anymore.
You misunderstand the nature of C strings.
A string is an array of characters with a low value ( '\0') marking the end of the string. Within the string some of the characters could be spaces (' ' or x20).
So the " t[i] != '\0' " condition marks the end of the loop.
A simple change:
if ( t[i] != ' ') {
lettercount++;
}
Will get your program working.
This for loop
for (int i = 0; t[i] != '\0'; i++)
iterates until the current character is the terminating zero character '\0' that is a null character. So the character is not counted.
In C there is the standard function isalpha declared in the header <ctype.h> that determines whether a character represents a letter.
Pay attention to that the user can for example enter punctuation symbols in a string. Or he can use the tab character '\t' instead of the space character ' '. For example his input can look like "~!##$%^&" where there is no any letter.
So it would be more correctly to write the loop the following way
size_t lettercount = 0;
for ( string s = t; *s; ++s )
{
if ( isalpha( ( unsigned char )*s ) ) ++lettercount;
}
printf("%zu\n", lettercount );
This statement
printf("/n");
shall be removed. I think instead you mean
printf("\n");
that is you want to output the new line character '\n'. But this character can be inserted in the previous call of printf as I showed above
printf("%zu\n", lettercount );
A null-terminator is the last leading element in a character array consisting of a string literal (e.g. Hello there!\0). It terminates a loop and prevent further continuation to read the next element.
And remember, a null-terminator isn't a space character. Both could be represented in the following way:
\0 - null terminator | ' ' - a space
If you want to count the letters except the space, try this:
#include <stdio.h>
#define MAX_LENGTH 100
int main(void) {
char string[MAX_LENGTH];
int letters = 0;
printf("Enter a string: ");
fgets(string, MAX_LENGTH, stdin);
// string[i] in the For loop is equivalent to string[i] != '\0'
// or, go until a null-terminator occurs
for (int i = 0; string[i]; i++)
// if the current iterated char is not a space, then count it
if (string[i] != ' ')
letters++;
// the fgets() reads a newline too (enter key)
letters -= 1;
printf("Total letters without space: %d\n", letters);
return 0;
}
You'll get something like:
Enter a string: Hello world, how are you today?
Total letters without space: 26
If a string literal has no any null-terminator, then it can't be stopped from getting read unless the maximum number of elements are manually given to be read till by the programmer.
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:
Example of output to screen
The function that I'm using is here.
//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
int length = strlen(plainText);
//turn capital letters into lower case letters
for (int i = 0; i < length; i++)
plainText[i] = tolower(plainText[i]);
//remove whitespace
for (int i = 0; i < length; i++) {
if (plainText[i] == ' ')
plainText[i] = plainText[i++];
printf("%c", plainText[i]);
}
printf("\n\n");
//remove punctuation from text
for (int i = 0; i < length; i++) {
if (ispunct(plainText[i]))
plainText[i] = plainText[i++];
printf("%c", plainText[i]);
}
}
Any help as to why the text is unchanged after if exits the loop would be appreciated.
Those for loops are not necessary. Your function can be modified as follows and I commented where I made those changes:
char* formatPlainText(char *plainText)
{
char *dest = plainText; //dest to hold the modified version of plainText
while ( *plainText ) // as far as *plainText is not '\0'
{
int k = tolower(*plainText);
if( !ispunct(k) && k != ' ') // check each char for ' ' and any punctuation mark
*dest++ = tolower(*plainText); // place the lower case of *plainText to *dest and increment dest
plainText++;
}
*dest = '\0'; // This is important because in the while loop we escape it
return dest;
}
From main:
int main( void ){
char str[] = "Practice ????? &&!!! makes ??progress!!!!!";
char * res = formatPlainText(str);
printf("%s \n", str);
}
The code does convert the string to lower case, but the space and punctuation removal phases are broken: plainText[i] = plainText[i++]; has undefined behavior because you use i and modify it elsewhere in the same expression.
Furthermore, you do not return plainText from the function. Depending on how you use the function, this leads to undefined behavior if you store the return value to a pointer and later dereference it.
You can fix the problems by using 2 different index variables for reading and writing to the string when removing characters.
Note too that you should not use a length variable as the string length changes in the second and third phase. Texting for the null terminator is simpler.
Also note that tolower() and ispunct() and other functions from <ctype.h> are only defined for argument values in the range 0..UCHAR_MAX and the special negative value EOF. char arguments must be cast as (unsigned char) to avoid undefined behavior on negative char values on platforms where char is signed by default.
Here is a modified version:
#include <ctype.h>
//eliminate all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
size_t i, j;
//turn capital letters into lower case letters
for (i = 0; plainText[i] != '\0'; i++) {
plainText[i] = tolower((unsigned char)plainText[i]);
}
printf("lowercase: %s\n", plainText);
//remove whitespace
for (i = j = 0; plainText[i] != '\0'; i++) {
if (plainText[i] != ' ')
plainText[j++] = plainText[i];
}
plainText[j] = '\0';
printf("no white space: %s\n", plainText);
//remove punctuation from text
for (i = j = 0; plainText[i] != '\0'; i++) {
if (!ispunct((unsigned char)plainText[i]))
plainText[j++] = plainText[i];
}
plainText[j] = '\0';
printf("no punctuation: %s\n", plainText);
return plainText;
}
I did this program to reverse the order of the words in the give string. (And it works)
i.e. Output: sentence first the is This
However I am stuck when it comes to adding another sentence to the array.
For example I need to have an array {"This is the first sentence", "And this is the second"} producing as output: sentence first the is This , second the is this And
int main() {
char str[] = {"This is the first sentence"};
int length = strlen(str);
// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
// putting the NULL character at the position of space characters for
next iteration.
str[i] = '\0';
// Start from next character
printf("%s ", &(str[i]) + 1);
}
}
// printing the last word
printf("%s", str);
return 0;
}
I am new to C so its not surprising that I got stuck even if the solution is quite easy. Any help would be appreciated! Thanks!
Since you already have the code to print the words of one string in reverse order, I would suggest making that a function which takes a single string as an argument, i.e.:
void print_words_reverse(char * const str) {
// your current code here
}
Then you can call it separately for each string:
char strings[][30] = {
"This is the first sentence",
"And this is the second"
};
for (int i = 0; i < sizeof(strings) / sizeof(*strings); ++i) {
print_words_reverse(strings[i]);
}
Note that since you are modifying the string (by replacing spaces with NUL bytes), the argument needs to be modifiable, which means you are not allowed to call it (in standard C) with a pointer to a string literal, which means you can't simply use const char *strings[] = { "first", "second" }. You could get rid of the ugly constant length (here 30) reserved for every string by making your code not modify the argument string. Or you could have a separate char array for each sentence and then use pointers to those (modifiable) strings.
First, you can try with a two-dimensional array or use an array of pointers.
Secondly, in your approach, you lose the initial value of your string, I don't know how important it is.
This is my fast approach using arrray of pointers.
#include <stdio.h>
#include <string.h>
static void print_word(const char *str)
{
for (int i = 0; str[i] && str[i] != ' '; i++)
printf("%c", str[i]);
putchar(' ');
}
int main(void)
{
int len;
const char *str[] = {"This is the first sentence",
"And this is second", NULL};
for (int i = 0; str[i]; i++) {
for (len = strlen(str[i]); len >= 0; len--) {
if (len == 0)
print_word(&str[i][len]);
else if (str[i][len] == ' ')
print_word(&str[i][len + 1]);
}
putchar('\n');
}
printf("Initial value of array of strings [%s | %s] \n", str[0], str[1]);
return 0;
}
output is:
sentence first the is This
second is this And
Initial value of array of strings [This is the first sentence | And this is second]
I suggest you using memcpy but without altering too much your code this seems to work
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_STRING_LENGTH 100
int main()
{
char *str[] = {"This is the first", "And this is the second sentence"};
const size_t NUM_STRING = sizeof(str)/sizeof(char*);
/*%z used to print size_t variables*/
printf("%zd strings found\n", NUM_STRING);
int length[2];
int i;
for (i=0; i<NUM_STRING; i++)
{
length[i] = strlen(str[i]);
}
printf("length initialized %d %d\n", length[0], length[1]);
// Traverse string from end
int j = 0;
char temp[MAX_STRING_LENGTH];
printf("\n\n");
for (j=0; j<NUM_STRING; j++)
{
/*Make sure the string respect the MAX_STRING_LENGTH limit*/
if (strlen(str[j])>MAX_STRING_LENGTH)
{
printf("ERROR: string %d exceding max string length %d defined in constant "
"MAX_STRING_LENGTH. Exiting from program.\n", j, MAX_STRING_LENGTH);
exit(1);
}
//reset temporary string
memset(temp, '\0', sizeof(temp));
//printf("temp variable reinitialized\n");
for (i = length[j] - 1; i >= 0; i--)
{
temp[i] = str[j][i];
if (str[j][i] == ' ')
{
// putting the NULL character at the position of space characters for next iteration.
temp[i] = '\0';
// Start from next character
printf("%s ", &(temp[i]) + 1);
}
}
// printing the last word
printf("%s ", temp);
}
printf("\n");
return 0;
}
why following code is giving garbage value ?
here I am trying to get an string as an input from user character by character. In the following code i have got input from user and stored in string[] array then in order to do some other operations i have stored the same in other array called temp_string[i]. But surprisingly i am getting garbage value in output.and also length calculated using strlen is not correct. can anybody look at this code and explain whats going wrong?
#include<stdio.h>
#include<stdio.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
char temp_string[i];
printf("%s", string);
i = 0;
while(string[i] != '\n')
{
temp_string[i] = string[i];
i++;
}
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
You forgot to add the null at the end of the string.
C strings are null-terminated, that means that all operations in c strings expect a null to mark the end of the string, including functions like strlen.
you can achieve that just adding:
string[i] = '\0';
After fill the string.
Another thing, what happens if the user enters a string bigger than 100? Is good to validate the input for these cases, otherwise you can get a buffer overflow.
You need to add a NULL - terminated at the end of your string. Add \0.
You need to put a '\0' char at the end of the string so strlen(), printf() and other C functions dealing with strings will work. That is how the C API knows it reached the end of the string.
Also, you don't want to set new characters at the memory space past the string array. So you better check that in your loop (and save a last array item to set the '\0').
while (ch != '\n' && i < 99)
{
ch = getchar();
string[i] = ch;
i++;
}
string[i] = '\0'; // set the string terminator past the end of the input
Remember to do the same after copying the characters to temp_string. (By the way, you can replace that loop with a call to strcpy(), that does exactly that, except it will end only when it finds a '\0'.)
You might also want to read What's the rationale for null terminated strings?
Here is your Final Code:
#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
char temp_string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
string[i]=NULL;
printf("%s", string);
i = 0;
while(string[i] != '\0')
{
temp_string[i] = string[i];
i++;
}
temp_string[i]=NULL;
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
In the above code what exactly you are missing is NULL or '\0' termination of the string. I just added it to make it useful.