char string doesn't work what the problem with "\0" - c++

I don't know what the problem is? My code doesn't work. :(
#include <iostream>
#include <string.h>
using namespace std;
bool isPalindrome(char* word){
int len = strlen(word);
if(len <= 1){
return true;
}else
if(word[0] == word[len-1]){
char n[len-1];
n[len-1]= "\0";
return isPalindrome(n);
}
return false;
}
int main(){
char *a = "alla";
bool b = isPalindrome(a);
cout<<b<<endl;
return 0;}
The error is "\0" , I don't know why.
My main function should be not right too.

I believe "\0" is a null-terminated 2 character C string consisting of a zero followed by a zero. Use '\0' instead, which is just a zero. Remember: use double quotes for strings and single quotes for single characters. You cannot assign a string to a string index location, so double quotes don't work like that, but you can assign a character to a string index location.
2nd error: read the documentation on strlen(). Create n with char n[len + 1];, NOT char n[len-1];, in order to make n the same length as the other string. Then, null terminate with n[len]= '\0';, not n[len - 1]= '\0';, since strlen doesn't count the null terminator in the string. I'm confused by your code though: what is the purpose of this n string? Lastly, you're writing outside your n array as you have it written! Since you made n have size len - 1, you would need to null terminate at index len - 2. len - 1 in your case is outside the array! Always null terminate inside the array at the index 1 smaller than the size of the array. When the compiler knows the side of the array, such as is the case with n, do it like this instead: n[sizeof(n) - 1] = '\0';.
You can't use a variable to set an array length in C by the way, and in C++ it may require len to be const to instantiate an array.

The Simple answer is that you should
use '\0' instead of "\0"
as n is a character array that you should use single quotation instead of double quotation
Hope this will Help

The assignment of element of character array should be with character only but in your case you are assigning to string. Note that ''/0'' is string. Try using assigning to '/0'.

Related

String array length C++ issue?

I've understood that string arrays end with a '\0' symbol. So, the following code should print 0, 1, 2 and 3. (Notice I'm using a range-based for() loop).
$ cat app.cpp
#include <iostream>
int main(){
char s[]="0123\0abc";
for(char c: s) std::cerr<<"-->"<<c<<std::endl;
return 0;
}
But it does print the whole array, including '\0's.
$ ./app
-->0
-->1
-->2
-->3
-->
-->a
-->b
-->c
-->
$ _
What is happening here? Why is the string not considered to end with '\0'? Do C++ collections consider (I imagine C++11) strings differently than in classical C++?
Moreover, the number of characters in "0123\0abc" is 8. Notice the printout makes 9 lines!
(I know that std::cout<< runs fine, as well as strlen(), as well as for(int i=s; s[i]; i++), etc., I know about the end terminator, that's not the question!).
s is of type char [9], i.e. an array containing 9 chars (including the null terminator char '\0'). Ranged-based for loop just iterators over all the 9 elements, the null terminator char '\0' is not considered specially.
Executes a for loop over a range.
Used as a more readable equivalent to the traditional for loop
operating over a range of values, such as all elements in a container.
for(char c: s) std::cerr<<"-->"<<c<<std::endl; produces code prototype equivalent to
{
auto && __range = s ;
auto __begin = __range ; // get the pointer to the beginning of the array
auto __end = __range + __bound ; // get the pointer to the end of the array ( __bound is the number of elements in the array, i.e. 9 )
for ( ; __begin != __end; ++__begin) {
char c = *__begin;
std::cerr<<"-->"<<c<<std::endl;
}
}
When you declare a char[] as char s[] = "0123\0abc" (a string literal), s becomes a char[9]. The \0 is included because it needs space too.
The range-based for-loop you use does not consider the char[9] as anything else than an array containing char with the extent 9 and will happily provide every element in the array to the inner workings of your loop. The \0 is just one of the chars in this context.
Be aware that char not necessarily needs to define a character only – it can be used to store any arbitrary 8-bit value (on some machines, char is wider, though, encountered one with a 16-bit char already – then there's no int8_t available...), although signed char or unsigned char – according to specific needs – should be preferred, as signedness of char is implementation defined (or even better: int8_t or uint8_t from cstdint header, provided they are available).
So your string literal actually is just an array of nine integral values (just as if you had created an int-array, only the type usually is narrower). A range based for loop will iterate over all of these nine 8-bit integers, and you get the output in your example.
These integral values only get a special meaning in specific contexts (functions), such as printf, puts or even operator>>, where they are then interpreted as characters. When used as C-strings, a 0 value inside such an array marks the end of the string – but this 0-character still is part of that string. For illustration: puts might look like this:
int puts(char const* str)
{
while(!*str) // stops on encountering null character
{
char c = *str;
// + get pixel representation of c for console, e. g 'B' for 66
// + print this pixel representation to current console position
// + advance by one position on console
++str;
}
return 0; // non-negative for success, could return number of
// characters output as well...
}
Here s is an array of char, so it includes \0 too.
When you use for(char c: s), the loop will search all char in the array.
But in C, the definition tells us:
A string is a contiguous sequence of characters terminated by and including the first null character.
And
[...] The length of a string is the number of bytes preceding the null character and the value of a string is the sequence of the values of the contained characters...
So, when you use C standard functions to print the array s as a string, you will see the result that you wanted. Example: printf("%s", s);
"the number of characters in "0123\0abc" is 8. Notice the printout makes 9 lines!"
Again, printf("%s; Len = %d", s, strlen(s)); runs fine!

setting char arrays equal to eachother with isdigit and isalpha

Im trying to set a char array equal to 2 other arrays depending on if the element in the first array is a number or a letter. The code makes logical sense to me but the output for the 2 other strings after the for loop doesn't correspond to the logic. Is it because of a missing null value somewhere in the other 2 loops or is the code itself invalid? arrayAlpha, arrayNum, and palind are all char arrays set to a length of 30 elements while string length was already determined before the for loop began.
for(int k=0; k<=stringLength; k++)
{
if( isalpha(palind[k])){
arrayAlpha[k]=palind[k];}
if ( isdigit(palind[k]))
{
arrayNum[k]=palind[k];
}
}
Given the input:
char palind[30] = "12345abcde";
arrayAlpha is garbage.
arrayNum is "12345"
However,
char palind[30] = "abcde12345";
arrayAlpha is "abcde".
arrayNum is garbage.
Thus, [k] is the problem when used in your arrayNum or arrayAlpha which doesn't start with 0.
Simple change will just be subtracting the length of the other.
arrayAlpha[k - strlen(arrayNum)] = palind[k];
arrayNum[k - strlen(arrayAlpha)] = palind[k];
since lengthOfPalind = lengthOfArrayAlpha + lengthOfArrayNum assuming palind only contains letters or numbers.

How do I take a characters and turn it into a string? C++

I'm just trying to use the alphabet to try and make words/names. When I do this the cout end up outputting nothing.
#include <iostream>
#include <ctime>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
string n;
n[0] = Alphabet[10];
n[1] = alphabet[4];
n[2] = alphabet[21];
n[3] = alphabet[8];
n[4] = alphabet[13];
cout << n << endl;
}
Your issue here is that n is an empty string, meaning you're trying to access indexes that don't exist.
To add characters to the string, you could use the string member function, push_back
n.push_back(Alphabet[10]);
n.push_back(alphabet[4]);
...
Alternatively, the += operator would also work:
n += Alphabet[10];
n += alphabet[4];
...
Furthermore, I'd suggest using .at() over the subscript operator ([]) with your strings, as .at() will do bounds checking for you (which would have made this issue a little more obvious).
When you create a string with string n;, an empty string is created. It has length zero, therefore trying to access character positions within the string with n[0] etc. does not work. These simply do not exist at that point.
As said in another answer, you can use the member function push_back to add a character to a string, increasing its length by one.
When you define n as string n;, then n will be an empty string (zero size and unspecified capacity), and accessing a string with an index beyond its size is undefined behaviour.
There are two principal ways to overcome this:
(1) Use operator += like in n += Alphabet[10];, such that the string object will adapt its size accordingly. Note that this may lead to realloc-operations internally from time to time.
(2) if you know the size in advance, with string n(5, ' ') you may reserve enough space in advance (and fill the string up with blanks in this case), such that realloc-operations will not have to occur.

C++ - A better way to create a null terminated c-style string of specific size with same character

I am looking to create a null terminated c-style string where every character is - (hyphen). I am using the following block of code:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n + 1] = '\0';
1) Is there a smarter C++ way to do this?
2) When I print the size of the string the output is n, not n + 1. Am I doing anything wrong or is null character never counted?
Edit:
Please consider this block of code instead of the one above:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n] = '\0';
And please ignore the question regarding size.
Is there a smarter C++ way to do this?
Sure, use a std::string to do that:
std::string s(n,'-');
const char* cstyle = s.c_str();
1) Is there a smarter C++ way to do this?
Using the String class:
std::string output_str(n,'-');
In case you need a string in old C style
output_str.c_str(); // Returns a const char*
2) When I print the size of the string the output is n, not n + 1. Am I doing anything wrong or is null character never counted?
In your code, the N caracter is not added. If the array was pre-filled with zero, strlen function will return N.

remove non alphabet characters from string c++ [duplicate]

This question already has answers here:
How to strip all non alphanumeric characters from a string in c++?
(12 answers)
Closed 6 years ago.
I'm trying to remove all non alphabet characters from an inputed string in c++ and don't know how to. I know it probably involves ascii numbers because that's what we're learning about. I can't figure out how to remove them. We only learned up to loops and haven't started arrays yet. Not sure what to do.
If the string is Hello 1234 World&*
It would print HelloWorld
If you use std::string and STL, you can:
string s("Hello 1234 World&*");
s.erase(remove_if(s.begin(), s.end(), [](char c) { return !isalpha(c); } ), s.end());
http://ideone.com/OIsJmb
Note: If you want to be able to handle strings holding text in just about any language except English, or where programs use a locale other than the default, you can use isalpha(std::locale).
PS: If you use a c-style string such as char *, you can convert it to std::string by its constructor, and convert back by its member function c_str().
If you're working with C-style strings (e.g. char* str = "foobar") then you can't "remove" characters from a string trivially (as a string is just a sequence of characters stored sequentially in memory - removing a character means copying bytes forward to fill the empty space used by the deleted character.
You'd have to allocate space for a new string and copy characters into it as-needed. The problem is, you have to allocate memory before you fill it, so you'd over-allocate memory unless you do an initial pass to get a count of the number of characters remaining in the string.
Like so:
void BlatentlyObviousHomeworkExercise() {
char* str = "someString";
size_t strLength = ... // how `strLength` is set depends on how `str` gets its value, if it's a literal then using the `sizeof` operator is fine, otherwise use `strlen` (assuming it's a null-terminated string).
size_t finalLength = 0;
for(size_t i = 0; i < strLength; i++ ) {
char c = str[i]; // get the ith element of the `str` array.
if( IsAlphabetical(c) ) finalLength++;
}
char* filteredString = new char[ finalLength + 1 ]; // note I use `new[]` instead of `malloc` as this is C++, not C. Use the right idioms :) The +1 is for the null-terminator.
size_t filteredStringI = 0;
for(size_t i = 0; i < strLength; i++ ) {
char c = str[i];
if( IsAlphabetical(c) ) filteredString[ filteredStringI++ ] = c;
}
filteredString[ filteredStringI ] = '\0'; // set the null terminator
}
bool IsAlphabet(char c) { // `IsAlphabet` rather than `IsNonAlphabet` to avoid negatives in function names/behaviors for simplicity
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
I do not want to spoil the solution so I will not type out the code, only describe the solution. For your problem think of iterating through your string. Start with that. Then you need to decide if the currently selected character is part of the alphabet or not. You can do this numerous different ways. Checking ASCII values? Comparing against a string of the alphabet? Once you decide if it is a letter, then you need to rebuild the new string with that letter plus the valid letters before and after that you found or will find. Finally you need to display your new string.
If you look at an ascii table, you can see that A-Z is between 65-90 and a-z is between 97-122.
So, assuming that you only need to remove those characters (not accentuated), and not other characters from other languages for example, not represented in ascii, all you would need to do is loop the string, verify if each char is in these values and remove it.