I have a wriiten a C program that contains a char array 'long_string' that looks something like this.
long_string[16] = "AHDAHDAHDAHDAHDA";
I wish to replace the letters in the string as follows:
A-0, H-1, D-2.
Could somebody tell me how could I achieve this? I tried to look online but most of the cases show the conversion of letters to there ASCII values which is not what I need. THank you for your time in advance :)
The way you have defined your string, it won't be null terminated (16 is not enough to fit in also the null terminator). Other than that, what you want should be fairly easy:
int i = 0;
char long_string[] = "AHDAHDAHDAHDAHDA";
int len = strlen(long_string);
for(i = 0; i<len; i++)
{
if(long_string[i] == 'A')
long_string[i] = '0';
else if(long_string[i] == 'H')
long_string[i] = '1';
// etc.
}
int i = 0;
for( ; i < size ; i++ ){
switch( long_string[i] ){
case 'A':
long_string[i] = '0';
break;
// and so on...
}
}
If you want to translate uppercase alpha chars, you can use a lookup table and index it with the char value less 'A', eg:
//ABCDEFGHIJKLMNOPQRSTUVWXYZ
const char xlat[]=("0 2 1 ");
..
..
newChar=xlat[oldChar-'A'];
or, for what you seem to want, the more general form:
const char xlat[]=("\x00\x20\x20\x02\x20\x20\x20\x01\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20");
Note that translating the chars into a set that includes '\0' will render the output array unuseable as a C-style string.
Related
I am writing a program that replaces characters in the user's input in C but I don't know how to replace the certain characters. Is there a certain method for C that replaces characters in a string? If you know python, then I want something a bit like this in python:
string.replace('certain_character','replacement_character')
Something like that, except for C, and not python.
This is my code that I have written so far:
#include <stdio.h>
int main(){
char str[BUFSIZ];
printf("Welcome To My Secret Language encoder!Enter some text: \n");
scanf("%s",str);
/*
Where I want to replace certain characters
*/
printf("Here is your text in secret language mode: %s \n",str);
}
I'm writing this code to learn C more, and that's why i'm not doing it in a higher level language like python.So, how do you replace certain characters in a string?
Nothing like that in C. You'll have to scan the string yourself:
#include <string.h>
char str[] = "I love cats";
int i;
for(i = 0; i < strlen(str); i++)
{
if(str[i] == 'c')
str[i] = 'b';
}
Now, if you're looking for a substring, you'll need something like strstr.
strchr finds the given character in a string, or returns NULL.
int main() {
int c;
while ( ( c = getchar() ) != EOF ) {
char const * found, * source = "abc", * dest = "xyz";
if ( ( found = strchr( "abc", c ) ) != NULL ) {
putchar( dest[ found - source ] );
} else {
putchar( c );
}
}
return 0;
}
If you have a lot of characters that you want to replace with other characters (like a Caesar cypher) you can build a lookup for yourself as follows:
#include <string.h>
char plain[] = "Hello there good people";
char encoder[26] = "ghijklmnopqrstuvwxyzabcdef";
char secret[100]; // long enough
int n = strlen(plain);
for(ii = 0; ii < n; ++ii) {
secret[ii] = encoder[(tolower(plain[ii]) - 'a')%26];
}
secret[n] = '\0';
This uses a couple of tricks:
cast all characters to lower case
subtract 'a' from the lowercase number - since a char is really just a number, we now have a == 0
Perform a modulo operation on the result so things that fall outside of the range of good characters don't cause a memory access error.
Add a '\0' at the end to make sure the string is properly terminated.
Copying things into a new string; obviously you could do an in-place replacement.
As written this will turn numbers (digits) and punctuation / symbols / spaces into characters. You could decide that anything that is not a letter is maintained - and maybe that only lower case letters are converted. In that case
#include <string.h>
char plain[] = "Hello there good people";
char encoder[26] = "ghijklmnopqrstuvwxyzabcdef";
char secret[100]; // long enough
int n = strlen(plain);
for(ii = 0; ii < n; ++ii) {
if(plain[ii] >= 'a' && plain[ii] <= 'z') {
secret[ii] = encoder[plain[ii] - 'a'];
}
else {
secret[ii] = plain[ii];
}
}
secret[n] = '\0';
there is no such function, you have to write one using strstr.
if you can use std::string, you can use string.replace()
Say you want to replace: A with z and b with X
char *replace(char *src, int replaceme, int newchar)
{
int len=strlen(src);
char *p;
for(p=src; *p ; p++)
{
if(*p==replaceme)
*p=newchar;
}
return src;
}
usage:
replace(string, 'A', 'z');
replace(string, 'b', 'X');
This is just the logic to do it, you need more statements in your code.
I'm looking for a simple solution for stripping numbers from a string.
Example: "GA1UXT4D9EE1" => "GAUXTDEE"
The occurrence of the numbers inside the string is erratic hence I cannot rely on functions such as scanf().
I'm new at programming in C.
Thanks for any help.
I will give you some tips:
You need to creat a new string.
Iterat over the original string.
Check if the current character is between the ascii values of numbers
If not, add it to the new string.
char stringToStrip[128];
char stripped[128];
strcpy(stringToStrip,"GA1UXT4D9EE1");
const int stringLen = strlen(stringToStrip);
int j = 0;
char currentChar;
for( int i = 0; i < stringLen; ++i ) {
currentChar = stringToStrip[i];
if ((currentChar < '0') || (currentChar > '9')) {
stripped[j++] = currentChar;
}
}
stripped[j] = '\0';
iterate through the string and check for the ascii value.
for(i = 0; i < strlen(str); i++)
{
if(str[i] >= 48 && str[i] <= 57)
{
// do something
}
}
I would agree that walking through would be an easy way to do it, but there is also an easier function to do this. You can use isdigit(). C++ documentation has an awesome example. (Don't worry, this also works in c.)
http://www.cplusplus.com/reference/cctype/isdigit/
Here is the code to do it.
int i;
int strLength = strlen(OriginalString);
int resultPosCtr = 0;
char *result = malloc(sizeof(char) * strLength);//Allocates room for string.
for(i = 0; i < strLength; i++){
if(!isdigit(OriginalString[i])){
result[resultPosCtr] = OriginalString[i];
resultPosCtr++;
}
}
result[resultPosCtr++] = '\0'; //This line adds the sentinel value A.K.A the NULL Value that marks the end of a c style string.
Everyone has it right.
Create a new char[] A.K.A. C style string.
Iterate over the original string
Check to see if the character at that iteration is a number
if not add to new string
I am like 3 weeks new at writing c code, so I am a newbie just trying some examples from a Harvard course video hosted online. I am trying to write some code that will encrypt a file based on the keyword.
The point is each letter of the alphabet will be assigned a numerical value from 0 to 25, so 'A' and 'a' will be 0, and likewise 'z' and 'Z' will be 25. If the keyword is 'abc' for example, I need to be able to convert it to its numerical form which is '012'. The approach I am trying to take (having learned nothing yet about many c functions) is to assign the alphabet list in an array. I think in the lecture he hinted at a multidimensional array but not sure how to implement that. The problem is, if the alphabet is stored as an array then the letters will be the actual values of the array and I'd need to know how to search an array based on the value, which I don't know how to do (so far I've just been returning values based on the index). I'd like some pseudo code help so I can figure this out. Thanks
In C, a char is an 8-bit integer, so, assuming your letters are in order, you can actually use the char value to get the index by using the first letter (a) as an offset:
char offset = 'a';
char value = 'b';
int index = value - offset; /* index = 1 */
This is hard to answer, not knowing what you've learned so far, but here's a hint to what I would do: the chars representing letters are bytes representing their ASCII values, and occur sequentially, from a to z and A to Z though they don't start at zero. You can cast them to ints and get the ascii values out.
Here's the pseudo code for how I'd write it:
Cast the character to a number
IF it's between the ascii values of A and Z, subtract it from A
ELSE Subtract it from the ASCII value of a or A
Output the result.
For what it's worth, I don't see an obvious solution to the problem that involves multidimensional arrays.
char '0' is the value 48
char 'A' is the value 65
char 'a' is the value 97
You said you want to learn how to search in the array:
char foo[26]; //your character array
...
...
//here is initialization of the array
for(int biz=0;biz<26;biz++)
{
foo[biz]=65+biz; // capital alphabet
}
...
...
//here is searching 1 by 1 iteration(low-yield)
char baz=67; //means we will find 'C'
for(int bar=0;bar<26;bar++)
{
if(foo[bar]==baz) {printf("we found C at the index: %i ",bar);break;}
}
//since this is a soted-array, you can use more-yield search algortihms.
Binary search algortihm(you may use on later chapters):
http://en.wikipedia.org/wiki/Binary_search_algorithm
The use of a multidimensional array is to store both the lower case and upper case alphabets in an array so that they can be mapped. An efficient way is using their ASCII code, but since you are a beginner, I guess this example will introduce you to handle for loops and multidimensional arrays, which I think is the plan of the instructor as well.
Let us first set up the array for the alphabets. We will have two rows with 26 alphabets in each row:
alphabetsEnglish[26][2] = {{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'},
{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}};
Now we can map elements of both cases.
int main()
{
int c,i,j;
char word[10];
printf("Enter a word:");
scanf("%s",word);
c=strlen(word);
printf("Your word has %d letters ", c);
for (i = 0; i < c; i++) //loop for the length of your word
{
for (j = 0; j <= 25; j++) //second loop to go through your alphabet list
{
if (word[i] == alphabetsEnglish[0][j] || word[i] == alphabetsEnglish[1][j]) //check for both cases of your alphabet
{
printf("Your alphabet %c translates to %d: ", word[i], j);
}
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *conv(char* str){
static const char* table = "abcdefghijklmnopqrstuvwxyz";
int size, *ret, *p;
if(NULL==str || *str == '\0') return NULL;
size = strlen(str);
ret=p=(int*)malloc(size*sizeof(int));
while(*str){
char *pos;
pos=strchr(table, tolower(*str++));
*p++ = pos == NULL ? -1 : pos - table;
}
return ret;
}
int main(void){
char *word = "abc";
int i, size = strlen(word), *result;
result = conv(word);
for(i=0;i<size;++i){
printf("%d ", result[i]);//0 1 2
}
free(result);
return 0;
}
How can I remove the '\n' from each string in this array?
I know that I can do something like this for a simple C-String, but I failed at using it in this case
cmd[strcspn(cmd, "\n")] = '\0';
I am also not sure if that would be the propper way or not.
The String will never contain any space or \n in the middle. They are also of a static length (6).
#include <stdlib.h>
unsigned char cmd[][6] = {
{"r123\n"},
{"r999\n"},
{"l092\n"},
{"l420\n"}};
void main(void) {
int i;
for(i = 0; i < (sizeof(cmd) / sizeof(cmd[0])); i++) {
printf("%s\n", cmd[i]);
}
}
Just do it by hand, it's easy!
If it's guaranteed to be only the last char in every word, and it's guaranteed to be there, than like this:
for (i = 0; i < elem_number; ++i){
cmd[i][strlen(cmd[i])-1] = 0;
}
If, on the other hand, you are unsure how many whitespace characters there will be at the end, but you know they will only be there at the end (there might be 0 in this case!) than this:
for (i = 0; i < elem_number; ++i){
for (j = 0; cmd[i][j] != 0; ++j){
if (isspace(cmd[i][j]))
cmd[i][j] = 0;
}
}
Voila!
If there will be whitespaces in the middle, then you have to define the desired behaviour: cut only the trailing whitespaces, cut the string in many little ones, or something completely different.
Oh, and one other sidenote:
everyone else seems to be using char = '\0'. In C, '\0' and 0 are equivalent, i.e. if ('\0' == 0) { ... } evaluates to true.
Sidenote 2: I used elem_number because I did not know if the number of elements is a parameter or hardcoded / know in advance. Substitute with what is appropriate.
Setting a character in a char array to \0 will truncate the string at that character.
So in your example setting the 5th character will do the job.
cmd[i][4] = '\0';
If the intended string can be less than 4 in length then don't hard-code to 4 but rather strlen(cmd[i])-1
Maybe you can use strrchr? Use in a loop if the string may contain several linebreaks.
for(i = 0; i< sizeof(cmd)/sizeof(unsigned char[6]);i++)
*strchr(cmd[i], '\n') = '\0';
I have a char array representing a double precision floating point number in hex form.
char *hex = ""402499999999999A"
I want to extract each char in hex as its own char array and read it into an unsigned int num. For example, I tried
sscanf((char *)&hex[3], "%X", &num);
But this doesn't give me the 4th char as an individual char array, it gives me the sub char array from the 4th position on, which I suppose is because arrays are given by the pointer of their first element.
Is there a better way to do this? I looked at strcpy and it seems that I can only copy the first n chars, so that's no good.
You can do this in many ways. One way is as follows (which is the correct way of how you were doing it):
char only_1_char[2] = {'\0', '\0'};
only_1_char[0] = hex[3];
sscanf(only_1_char, "%X", &num);
and a more efficient solution:
if (hex[3] <= '9')
num = hex[3] - '0';
else
num = hex[3] - 'A' + 10;
This is just a sample, though. In truth you need to take care of invalid input and lower cases if that is a possibility.
Try something like this:
for(i = 0; src[i] != 0; i++) {
if(src[i]) <= '9') {
dest[i] = src[i] - '0';
} else {
dest[i] = toupper(src[i]) - 'A' + 10;
}
}
It can be improved with error handling (e.g. detect if "src[i]" contains a valid/sane character).