Need help removing empty character in C - c

This should be relatively simple.
I've got a string/character pointer that looks like this
" 1001"
Notice the space before the 1. How do I remove this space while still retaining the integer after it (not converting to characters or something)?

The simplest answer is:
char *str = " 1001";
char *p = str+1; // this is what you need

If the space is at the beginning of string.You also can do it.
char *str = " 1001";
char c[5];
sscanf(str,"%s",c);
printf("%s\n",c);
%s will ignore the first space at the beginning of the buffer.

One solution to this is found here: How to remove all occurrences of a given character from string in C?
I recommend removing the empty space character or any character by creating a new string with the characters you want.
You don't seem to be allocating memory so you don't have to worry about letting the old string die.

If it is a character pointer, I believe
char* new = &(old++);
Should do the trick

I'm guessing your reading in a String representation of an integer from stdin and want to get rid of the white space? If you can't use the other tricks above with pointers and actually need to modify the memory, use the following functions.
You can also use sprintf to get the job done.
I'm sure there is more efficient ways to trim the string. Here is just an example.
void trim(unsigned char * str)
{
trim_front(str);
trim_back(str);
}
void trim_front(unsigned char * str)
{
int i = 0;
int index = 0;
int length = strlen(str);
while(index < length && (str[index] == ' ' || str[index] == '\t' || str[index] == '\n'))
{
index++;
}
while(index < length)
{
str[i] = str[index];
i++;
index++;
}
}
void trim_back(unsigned char * str)
{
int i;
for(i = 0; str[i] != ' ' && str[i] != '\n' && str[i] != '\t' && str[i] != '\0'; i++);
str[i] = '\0';
}

Related

Why is the last character "?" in this string function

I have the following string function:
char * to_upper(const char * str) {
char * upper = malloc(strlen(str)+1);
int i;
for (i=0; str[i] != 0; i++)
upper[i] = toupper(str[i]);
upper[i+1] = '\0';
return upper;
}
However, when I call it, it adds a "?" to the end (probably an invalid character). If I change the last line, from upper[i+1] = '\0' to upper[i] = '\0', it works as expected. What is wrong then with code above?
Additionally, is this the right way to allocate for the string?
char * upper = malloc(strlen(str)+1);
Or should I instead do:
char upper[strlen(str)+1];
Update: my error above is because length starts at 1, index starts at 0. How should I initialize the string though?
Your code is fine, you just need to remove the +1 as you found out. The for loop ends when str[i] is equal to '\0', so it makes sense that upper[i] should then be set to '\0' as well.
Your string initialization is fine.
I fixed the answer, accoridng to comments:
char * to_upper(const char * str) {
char* upper = malloc(strlen(str));
int i;
for (i=0; str[i] != '\0'; i++)
upper[i] = toupper(str[i]);
upper[i] = '\0';
return upper;
}
With the comments i saw the error in my and your logic. The null string is already there, hence we fall out of the for at str[i] == '\0'. So we know i is the index we need to set as \0 in upper.

Only first char of user input used in array

I am writing some code for a nanokernel, which means I can't use the standard library, although I have implemented functions for printing strings and getting chars from the keyboard.
Right now I have the program set up to take chars from the keyboard and put them into an array. The string is then printed out. I expect the string printed out to look exactly like what was inputted by the user.
The issue is that it seems that the only char being put into the string is the first char inputted on the keyboard.
here is the relevant code for putting the chars into an array:
void stringin(char str[]) { // takes a string, puts it in str
int i = 0;
for (i = 0; str[i] != '\n' && str[i] != '\033';) {
str[i] = getch();
if (str[i] != '\n' && str[i] != '\033') {
i++;
}
calctime(1000000); // waits for a bit so that we don't flood the array
}
if (str[i] == '\n') newline(1);
str[i++] = '\0';
}
I have used both a printing function and a strcmp() implementation to test the contents of the string, so nothing seems to be going wrong with printing the string.
Based on the comments, str is passed to stringin with the buffer uninitialized.
Since the following loop terminates based on the value of str[i] before str[i] is actually initialized, the results are undefined.
for (i = 0; str[i] != '\n' && str[i] != '\033';) {
str[i] = getch();
....

Find spaces and alphanumeric characters in a string

I need to develop a function that goes through a character string and detects letters (lower and upper cases), digits 0-9 and spaces ' '. If the functions finds only valid characters (the characters listed before) it returns 1 otherwise(if the string has characters like !,&,/,£, etc.) it returns 0. I am aware of a function that finds characters and digits which is isalnum().That is not helpful to find spaces. Does anyone can provide inbuilt or manual function which can detect characters,digits and spaces all together.
I've developed mine as under but function does not detect invalid character !,&,/,£ etc. in middle of the string and therefore it does not return the value I expect.
for (i=0; i<strlen(str); i++) {
if ((str[i]>='A' && str[i]<='Z') || str[i] == ' ' || (str[i]>='a' && str[i]<='z') || (str[i]>='0' && str[i]<='9'))
for (i=0; i<strlen(str); i++) {
char *p = str;
while (*p) {
if (isalnum((unsigned char) *p) || *p == ' ') {
res =1;
} else {
res = 0;
}
p++;
}
}
You can make the code more succinct:
int Validate_Alphanumeric(char *str)
{
unsigned char *ptr = (unsigned char *)str;
unsigned char uc;
while ((uc = *ptr++) != '\0')
{
if (!isalnum(uc) && uc != ' ')
return 0;
}
return 1;
}
Amongst other things, this avoids reevaluating strlen(str) on each iteration of the loop; that nominally makes the algorithm quadratic as strlen() is an O(N) operation and you would do it N times, for O(N2) in total. Either cache the result of strlen(str) in a variable or don't use it at all. Using strlen(str) requires the entire string to be scanned; the code above will stop at the first punctuation or other verboten character without scanning the whole string (but the worst case performance, for valid strings, is O(N)).
I came up with a function that goes through the string and that is able to return 0 if an invalid character (ex. $&$&&(%$(=()/)&)/) is found.
int Validate_Alphanumeric (char str[]) {
int i;
int res;
int valid=0;
int invalid=0;
const char *p = str;
while (*p) {
if (isalnum((unsigned char) *p) || *p == ' ') {
valid++;
} else {
invalid++;
}
p++;
}
if (invalid==0)
res=1;
else
res=0;
return res;
}

Array of Char in C

I'm trying to create a function that get a string, taking char by char:
char * GetString (int dim) // dim is the size of the string
{
char c, *S;
int i = 0;
S = (char*)malloc(dim*(sizeof(char));
while ((c=getchar() != '\n') && (i < dim) && (c != EOF))
{
S[i] = c;
i++;
}
S[i] = '/0';
return S;
}
The problem is when i try to use a "printf" in this function, trying to see if the input was taken correctly, it shows me strange characters, not the ones i inserted. I don't know what i'm missing.
Thanks very much.
This should be a backslash:
S[i] = '\0';
Make sure your compiler warnings are turned on and you're paying attention to them. '/0' is a non-standard multi-character integer literal.
Backslash zero '\0' is the C string NUL-terminator you're after.
Also, in the case where your input is larger than dim, you are overrunning your buffer, writing one byte more than you allocated. I would suggest allocating dim+1 bytes.
Finally, there's no point in multiplying by sizeof(char) - it is 1 by definition.
P.S. Now is an excellent time to learn how to use a debugger. If you're using GNU tools: gcc -Wall -Werror main.c then gdb a.out, and type r to run.
This '/0' is a character constant which value is implementation defined. So you have to replace it with escape character '\0'.
Also you have to allocate dim + 1 bytes if you want to append exactly dim characters with the terminating zero.
The function can look like
char * GetString( int dim )
{
char *s;
int i;
s = ( char* )malloc( ( dim + 1 ) *( sizeof( char ) );
i = 0;
while ( i < dim && ( ( c = getchar() ) != '\n') && ( c != EOF ) )
{
s[i++] = c;
}
s[i] = '\0';
return s;
}
Thanks to Vlads from Moscow for the right snippets. The problem was here:
while (c = getchar() != '\n')
It's wrong, the right way:
while ((c=getchar()) != '\n')
The code had an amazingly simple problem: you missed parentheses around c=getchar(). Try ((c=getchar()) != '\n') instead of (c=getchar() != '\n')
The code has other problems also, like using /0 instead of \0
Here is the rectified code:
#include <stdio.h>
#include <stdlib.h>
char * GetString (int dim) // dim is the size of the string
{
char c, *S;
int i = 0;
S = (char*)malloc(dim*(sizeof(char)));
while (((c=getchar()) != '\n') && (i < dim) && (c != EOF))
{
S[i] = c;
i++;
}
S[i] = '\0';
return S;
}
int main()
{
char *s;
s = GetString(10);
printf("%s\n", s);
free(s);
return 0;
}

why below code is giving garbage value?

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.

Resources