How Sorting a String by ASCII order - c++

I just make a program to sort a string in alphabetically order, but i have problem if i am input number it's not shown in output . How i sort in ASCII order. Any one can help ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_string(char*);
int main()
{
char string[100];
printf("Enter some text\n");
gets(string);
sort_string(string);
printf("%s\n", string);
return 0;
}
void sort_string(char *s)
{
int c, d = 0, length;
char *pointer, *result, ch;
length = strlen(s);
result = (char*)malloc(length+1);
pointer = s;
for ( ch = 'A' ; ch <= 'z' ; ch++ ) // i don't know how add range
{
for ( c = 0 ; c < length ; c++ )
{
if ( *pointer == ch )
{
*(result+d) = *pointer;
d++;
}
pointer++;
}
pointer = s;
}
*(result+d) = '\0';
strcpy(s, result);
free(result);
}
Sorry if my code still bad, i am still learn c++

When you look at the ASCII table, the number '0' starts on 0x30 and ends with a '9' at 0x39. In your loop, the first letter starts with an 'A', on 0x41.
Just start your loop from '0' to 'z', and it'll include the numbers too. (It will also include signs such as <, #, etc...)

Related

Why can't I change the pointer's content when in a loop?

I'm given a string and i need to display all strings that can be formed removing one letter at a time.
For example,for "abbc" i should display "bbc"
"abc"
"abc"
and "abb"
Here is my code:
int main()
{
char s[41]="abbc",*p;
int n=strlen(s);
p=s;
int i=0;
while(i<n)
{
strcpy(p+i,p+i+1);
cout<<p<<" ";
i++;
strcpy(p,s);
}
return 0;
}
It keeps showing bbc bc bc bc as if strcpy(p,s); wasn't wrote. Why can't I give a value to the pointer p in a loop?
To output substrings of a string according to your description there is no need to change the original string.
This call
strcpy(p+i,p+i+1);
has 1) undefined behavior (because the ranges are overlapped) 2) and changes the original string.
This call
strcpy(p,s);
does not make sense because the string is copied into itself due to this assignment
p=s;
The task can be done using ordinary for-loops. For example (a C++ program)
#include <iostream>
int main()
{
const char *s = "abbc";
for ( size_t i = 0; s[i] != '\0'; i++ )
{
for ( size_t j = 0; s[j] != '\0'; j++ )
{
if ( j != i ) std::cout << s[j];
}
std::cout << '\n';
}
return 0;
}
The program output is
bbc
abc
abc
abb
Or (a C program)
#include <stdio.h>
int main(void)
{
const char *s = "abbc";
for ( size_t i = 0; s[i] != '\0'; i++ )
{
for ( size_t j = 0; s[j] != '\0'; j++ )
{
if ( j != i ) putchar( s[j] );
}
putchar( '\n' );
}
return 0;
}
Here is a pure C version. It removes the last character from the string and stores it. After that it replaces each character with the one that came after it, until all have been replaced. At the end the string will contain the substring starting at the second character.
#include <string.h>
#include <stdio.h>
int main()
{
char s[41] = "abbc";
int n;
char c, tmp;
n = strlen(s);
c = 0;
while( n > 0 )
{
n--;
tmp = c;
c = s[n];
s[n] = tmp;
printf( "%s\n", s );
}
return 0;
}
p and s is pointing to the same memory. The memory is modified at each loop, so after the first loop n is no longer valid as the length of the string.
loop 1: p & s = "abbc", i=0, n=4
p+0 points to "abbc", p+1 points to "bbc"
value of s after strcpy(p+0, P+1) is "bbc"
loop 2: p & s = "bbc", i=1, n=4
p+1 points to "bc", p+1+1 points to "c"
value of s after strcpy(p+1, P+2) is "bc"
loop 3: p & s = "bc", i=2, n=4
p+2 points to null or "", p+3 points to something after string
value of s after strcpy(p+2, p+3) is undifined but likely remaining "bc"
loop 4: nothing treally change from above as you now are outside string

Converting array of char into array of integers? [duplicate]

How could I change an array of character (string) to an integer number without using any ready function (ex atoi();) for example :-
char a[5]='4534';
I want the number 4534 , How can I get it ?
Without using any existing libraries, you have to:
Convert character to numeric digit.
Combine digits to form a number.
Converting character to digit:
digit = character - '0';
Forming a number:
number = 0;
Loop:
number = number * 10 + digit;
Your function will have to check for '+' and '-' and other non-digits characters.
First of all this statement
char a[5]='4534';
will not compile. I think you mean
char a[5]="4534";
^^ ^^
To convert this string to a number is enough simple.
For example
int number = 0;
for ( const char *p = a; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
Or you could skip leading white spaces.
For example
int number = 0;
const char *p = s;
while ( std::isspace( ( unsigned char )*p ) ) ++p;
for ( ; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
If the string may contain sign '+' or '-' then you can check at first whether the first character is a sign.
You can go like this
It's working
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char a[5] = "4534";
int converted = 0;
int arraysize = strlen(a);
int i = 0;
for (i = 0; i < arraysize ; i++)
{
converted = converted *10 + a[i] - '0';
}
printf("converted= %d", converted);
return 0;
}
I prefer to use the std::atoi() function to convert string into a number data type. In your example you have an non-zero terminated array "\0", so the function will not work with this code.
Consider to use zero terminated "strings", like:
char *a = "4534";
int mynumber = std::atoi( a ); // mynumber = 4534

Creating a word shifter

For an assignment, I am working on creating a word shifter in C++. I have little to no experience with C++ so it has been very difficult. I think I am really close but just missing some syntax that is part of C++. Any help would be appreciated greatly.
string s = phrase;
int length = s.length();
//find length of input to create a new string
string new_phrase[length];
//create a new string that will be filled by my for loop
for (int i=0; i<length; i++)
//for loop to go through and change the letter from the original to the new and then put into a string
{
int letter = int(s[i]);
int new_phrase[i] = letter + shift;
//this is where I am coming up with an error saying that new_phrase is not initialized
if (new_phrase[i] > 122)
//make sure that it goes back to a if shifting past z
{
new_phrase[i] = new_phrase[i] - 26;
}
}
cout << new_phrase<< endl;
Considering your syntax,I wrote an example for you.Besides,it is conventional
to write comment before it's relevant code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//test value;
int shift = 3;
string s = "hello string";
//find length of input to create a new string
int length = s.length();
//create a new string.it's length is same as 's' and initialized with ' ';
string new_phrase(length, ' ');
for (int i=0; i<length; i++)
{
//no need to cast explicitly.It will be done implicitly.
int letter = s[i];
//It's assignment, not declaration
new_phrase[i] = letter + shift;
//'z' is equal to 126.but it's more readable
if (new_phrase[i] > 'z')
{
new_phrase[i] = new_phrase[i] - ('z' - 'a' + 1);
}
}
cout << new_phrase<< endl;
}
This should work.
// must be unsigned char for overflow checking to work.
char Shifter(unsigned char letter)
{
letter = letter + shift;
if (letter > 'z')
letter = letter - 26;
return letter;
}
// :
// :
string new_phrase = phrase; // mainly just allocating a string the same size.
// Step throught each char in phrase, preform Shifter on the char, then
// store the result in new_phrase.
std::transform(phrase.begin(), phrase.end(), new_phrase.begin(), Shifter);
cout << new_phrase<< endl;
UPDATE: made letter unsigned, so the overflow check works.
Try and investigate this code
#include <iostream>
#include <string>
#include <cctype>
void ShiftRight( std::string &s, std::string::size_type n )
{
if ( n >= 'Z' - 'A' + 1 ) return;
for ( char &c : s )
{
bool lower_case = std::islower( c );
c = std::toupper( c );
c = ( c + n -'A' ) % ('Z' -'A' + 1 ) + 'A';
if ( lower_case ) c = std::tolower( c );
}
}
int main()
{
std::string s( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
std::cout << s << std::endl << std::endl;
for ( std::string::size_type i = 1; i <= 'Z' -'A' + 1; i++ )
{
std::str std::string s( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
ShiftRight( s, i );
std::cout << s << std::endl;
}
return 0;
}
The output is
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ
As for your code then it of course is wrong. You have not to define an array of strings. And do not use magic numbers as for example 122.
Also you may include in my code a check that a next symbol is an alpha symbol.

Counting the frequency of characters in a file. C++

The task is to print the (given text file) encountered Latin characters using the frequency table (without distinguishing between uppercase and lowercase letters) to file f1. The table must be sorted alphabetically.
So far my program only counts the letter A. I'm having problems with creating the loops which go through the whole alphabet and prints the table into another file, could you help me with those?
#include <stdio.h>
const char FILE_NAME[] = "yo.txt";
#include <stdlib.h>
#include <iostream>
using namespace std;
int main() {
int count = 0; /* number of characters seen */
FILE *in_file; /* input file */
/* character or EOF flag from input */
int ch;
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
system("Pause");
exit(8);
}
while (1) {
char cMyCharacter = 'A';
int value = (int)cMyCharacter;
ch = fgetc(in_file);
if (ch == EOF){
break;
}
int file_character = (int) ch;
if (file_character == value || file_character == value+ 32) {
count++;
}
}
printf("Number of characters in %s is %d\n", FILE_NAME, count);
char cMyCharacter = 'A';
int iMyAsciiValue = (int)cMyCharacter;
cout << iMyAsciiValue;
system("Pause");
fclose(in_file);
return 1;
}
First, get an array of size 26 for frequencies of a to z
int freq[26] = {0};
freq[0] for 'a', freq[1] for 'b', etc.
Second, change
if (file_character == value || file_character == value+ 32)
to
if (file_character >= 'a' && file_character <= 'z')
for all the lower-case alphabets (i.e. 'a' to 'z').
Third, get index and count by
freq[file_character - 'a']++;
, file_character - 'a' calculates the index, and the rest does count.
Fourth, print the freq array.
Fifth, add
else if (file_character >= 'A' && file_character <= 'Z')
for upper-case characters, and change subsequent codes accordingly.
It is your homework, you should try to figure out the whole program yourself. I hope this answer provides enough hints for you.

producing all anagrams in a string c++

I saw this problem online, and I was trying to solve it in C++. I have the following algorithm:
char permutations( const char* word ){
int size = strlen( word );
if( size <= 1 ){
return word;
}
else{
string output = word[ 0 ];
for( int i = 0; i < size; i++ ){
output += permutations( word );
cout << output << endl;
output = word[ i ];
}
}
return "";
}
For example, if I have abc as my input, I want to display abc, acb, bac, bca, cab, cba.
So, what I'm trying to do is
'abc' => 'a' + 'bc' => 'a' + 'b' + 'c'
=> 'a' + 'c' + 'b'
so I need o pass a word less char every function call.
Could someone please help how to do it?
I suggest doing it using the algorithm header library in C++, much easier; and as a function can be written like this:
void anagram(string input){
sort(input.begin(), input.end());
do
cout << input << endl;
while(next_permutation(input.begin(), input.end()));
}
However since you want it without the STL, you can do it like so:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap (char *x, char *y)
{
char ch = *x;
*x = *y;
*y = ch;
};
void permutate_(char* str, size_t index )
{
size_t i = 0;
size_t slen = strlen(str);
char lastChar = 0;
if (index == slen )
{
puts(str);
return;
}
for (i = index; i < slen; i++ )
{
if (lastChar == str[i])
continue;
else
lastChar = str[i];
swap(str+index, str+i);
permutate_(str, index + 1);
swap(str+index, str+i);
}
}
// pretty lame, but effective, comparitor for determining winner
static int cmpch(const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
// loader for real permutor
void permutate(char* str)
{
qsort(str, strlen(str), sizeof(str[0]), cmpch);
permutate_(str, 0);
}
Which you can call by sending it a sorted array of characters,
permutate("Hello World");
The non-STL approach was gotten from here.
The STL is wonderful:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void permutations(const char *word) {
string s = word;
sort(s.begin(), s.end());
cout << s << endl;
while(next_permutation(s.begin(), s.end()))
cout << s << endl;
}
int main() {
permutations("abc");
return 0;
}
Now, next_permutation can be implemented quite simply. From the end of the string, iterate backwards until you find an element x which is less than the next element. Swap x with the next value larger than x in the remainder of the string, and reverse the elements coming afterwards. So, abcd becomes abdc since c < d; cdba becomes dabc since c < d and we flip the last three letters of dcba; bdca becomes cabd because b < d and we swap b for c.