Replace a few characters in a string literal using C++ - c++

i have
cost char* a="test_r.txt"
i want to strip the _r and add _n instead of it so that it becomes "test_n.txt"
and save it in const char* b;
what is the easiest way to do it ?

You can't directly modify the contents of a, so you'll need some copying:
std::string aux = a;
aux[5] = 'n';
const char* b = aux.c_str();

Like mentioned before, if you put your const char * into a std::string, you can change your characters. Regarding the replacing of a constant that is longer than one character you can use the find method of std::string:
const char *a = "test_r_or_anything_without_r.txt";
std::string a_copy(a);
std::string searching("_r");
std::string replacing("_n");
size_t pos_r = 0;
while (std::string::npos != (pos_r = a_copy.find(searching, pos_r)))
{
a_copy.replace(a_copy.begin() + pos_r,
a_copy.begin() + pos_r + searching.length(),
replacing.begin(), replacing.end());
}
const char *b = a_copy.c_str();

Related

How do I call a function multiple times with different parameters?

Fairly new to C++ here. I am trying to figure out if I can optimize my code by not calling the same function multiple times. For example see below:
funcCall is a standalone function so it cannot be removed, all it needs to know is those three paramters..
const char *a = "H";
const char *b = "e";
const char *c = "l";
const char *d = "l";
const char *e = "o";
const char *f = "Hi";
funcCall(f,a,b);
funcCall(f,c,d);
funcCall(f,d,e);
void funcCall(const char *one, const char *two, const char *three)
{
//Kindly ignore the syntax
//open the file and write the first two parameters to it
fopen(three.txt);
fwrite(one,two,three.txt); //ignore syntax
fclose(three.txt);
}
You can make an array of the characters, and loop over it two at a time, like so:
char abcdef[] = "Helllo";
const char* hi = "Hi";
for (char* p = abcdef; p < abcdef + 6; p += 2) {
funcCall(hi, p[0], p[1]);
}
This differs from your example in that it passes characters as the second and third arguments to funcCall, rather than null-terminated character strings.
After your edit, it looks like the parameters are really supposed to be strings, not just characters, so you'd want to have an array of strings rather than an array of characters. So you can do something like
std::vector<const char*> args = {"One", "Two", "Three"};
std::vector<const char*> files = {"A.txt", "B.txt", "C.dat"};
const char* hi = "Hi";
for (int i = 0; i < std::min(args.size(), files.size()); ++i) {
funcCall(hi, args[i], files[i]);
}
where funcCall takes const char* arguments as in your example. (It would probably be better to use std::string.)

C++ - How to append a char to char*?

I've tried so may ways on the Internet to append a character to a char* but none of them seems to work. Here is one of my incomplete solution:
char* appendCharToCharArray(char * array, char a)
{
char* ret = "";
if (array!="")
{
char * ret = new char[strlen(array) + 1 + 1]; // + 1 char + 1 for null;
strcpy(ret,array);
}
else
{
ret = new char[2];
strcpy(ret,array);
}
ret[strlen(array)] = a; // (1)
ret[strlen(array)+1] = '\0';
return ret;
}
This only works when the passed array is "" (blank inside). Otherwise it doesn't help (and got an error at (1)). Could you guys please help me with this ? Thanks so much in advanced !
Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.
To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.
Why you don't use std::string? it has .append method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way
bool AppendCharToCharArray( char *array, size_t n, char c )
{
size_t sz = std::strlen( array );
if ( sz + 1 < n )
{
array[sz] = c;
array[sz + 1] = '\0';
}
return ( sz + 1 < n );
}
If you need a function that will contain a copy of the original array plus the given character then it could look the following way
char * CharArrayPlusChar( const char *array, char c )
{
size_t sz = std::strlen( array );
char *s = new char[sz + 2];
std::strcpy( s, array );
s[sz] = c;
s[sz + 1] = '\0';
return ( s );
}
The specific problem is that you're declaring a new variable instead of assigning to an existing one:
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
and trying to compare string values by comparing pointers:
if (array!="") // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string
although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.
The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string and it will manage all the memory allocation for you:
std::string appendCharToString(std::string const & s, char a) {
return s + a;
}
char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;
OUTPUT:
test

Remove items from a char * C++

I am trying to remove characters from a char pointer and would like to store them back in a new char pointer variable let's say "temp". So I would have something like this:
char *test = "1#2#3$4%5^6&7*8!9#1#0";
char *temp = "";
then remove the "#,#,$,%,^,*,!,#,#," and place the new values of "12345678910" into *temp. This would make temp be equal to "12345678910".
Is this possible?
I have been doing this with string but I really need to do this with the char pointers. Here is how I have done this with string:
std::string str("1#2#3$4%5^6&7*8!9#1#0");
std::string temp("");
char chars[] = "##$%^&*!";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
temp = str;
So you see here I am doing this all will strings but I just cannot seem to get away with asigning a char * variable like test to a string because its an illegal conversion. However why am I able to set my char * variables equal to string like so?
char *test = "123456789";
However this is illegal?
std::string str("1#2#3$4%5^6&7*8!9#1#0");
char chars[] = "#";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
char *test = str; //Illegal point
Thank you for your time.
change
char *test = str;
into:
char *test = str.c_str();
c_str is a method that creates c style char array from original string for you.
EDIT: this is a more safe way, a copy of the c string will be obtained:
#include <cstring>
#include <cstdlib>
...
char *test = strdup(str.c_str());
... // process the string
free(test);
Here you have a reference to std string class.
Manpage for strdup.
Anything you can do with iterators you can also do with pointers to an array. Say, an array of chars:
char str[] = "1#2#3$4%5^6&7*8!9#1#0";
char chars[] = "#";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
*std::remove(str, str+strlen(str), chars[i])=0;
}
Notice that I used the fact that std::remove returns an iterator (in this case char*) to the "one after last" element and set that char to 0 - making sure it stays a zero-delimited string

C++ String and char * c stype strings

I have a c library which use char arrays as strings and i want to use c++ std::string on my code,
could someone help me how can i convert between char * c style strings and STL library strings ?
for example i have :
char *p="abcdef";
string p1;
and
string x="abc";
char *x1;
how can i convert p to p1 and x to x1
Use string's assignment operator to populate it from a char *:
p1 = p;
Use string's c_str() method to return a const char *:
x1 = x.c_str();
From char* to std::string :
char p[7] = "abcdef";
std::string s = p;
From std::string to char* :
std::string s("abcdef");
const char* p = s.c_str();
You can construct a std::string from a C string thus:
string p1 = p;
You can get a const char * from a std::string thus:
const char *x1 = x.c_str();
If you want a char *, you'll need to create a copy of the string:
char *x1 = new char[x.size()+1];
strcpy(x1, x.c_str());
...
delete [] x1;
string has a constructor and an assignment operator that take a char const* as an argument, so:
string p1(p);
or
string p1;
p1 = p;
Should work. The other way around, you can get a char const* (not a char*) from a string using its c_str() method. That is
char const* x1 = x.c_str();
#include <string.h>
#include <stdio.h>
// Removes character pointed to by "pch"
// from whatever string contains it.
void delchr(char* pch)
{
if (pch)
{
for (; *pch; pch++)
*pch = *(pch+1);
}
}
void main()
{
// Original string
char* msg = "Hello world!";
// Get pointer to the blank character in the message
char* pch = strchr(msg, ' ');
// Delete the blank from the message
delchr(pch);
// Print whatever's left: "Helloworld!"
printf("%s\n", msg);
}

Add 2 chars without using strncpy?

How would I manually concatenate two char arrays without using the strncpy function?
Can I just say char1 + char2?
Or would I have to write a for loop to get individual elements and add them like this:
addchar[0] = char1[0];
addchar[1] = char1[1];
etc
etc
addchar[n] = char2[0];
addchar[n+1] = char2[1];
etc
etc
To clarify, if
char1 = "happy"
char2 = "birthday"
I want addchar to = happybirthday
For a C-only solution use strncat:
char destination[80] = "";
char string1[] = "Hello";
char string2[] = " World!";
/* Copy string1 to destination */
strncat(destination, string1, sizeof(destination));
/* Append string2 to destination */
strncat(destination, string2, sizeof(destination) - sizeof(string1));
Note that the strn* family of string functions are safer than the ones without n, because they avoid the possibility of buffer overruns.
For a C++ solution, simply use std::string and operator+ or operator+=:
std::string destination("Hello ");
destination += "World";
destination += '!';
If you consider two trivial loops to be "manual", then yes, without using the standard library this is the only way.
char *append(const char *a, const char *b) {
int i = 0;
size_t na = strlen(a);
size_t nb = strlen(b);
char *r = (char*)calloc(na + nb + 1, 1);
for (i = 0; i < na; i++) {
r[i] = a[i];
}
for (i = 0; i < nb; i++) {
r[na + i] = b[i];
}
return r;
}
Remember to call free.
If you're using c++ just use an std::string. With std::strings, the + operator is supported, so you can do string1+string2.
Without using library functions, here is the procedure:
1. Point to the first character in string1.
2. While the current character at the pointer is not null, increment the pointer.
3. Create a "source" pointer pointing to string2.
4. While the character at the "source" location is not null:
4.1. Copy the character from the "source" location to the location pointed to by the String1 pointer.
4.2. Increment both pointers.
Unless this is homework, use C++ std::string for your text.
If you must use C style strings, use the library functions.
Library functions are optimized and validated, reducing your development time.
Alright, you want something like this:
char1 + char2
First, let's see the insane solution:
C:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length_left = strlen(a_Left);
unsigned int length_right = strlen(a_Right);
unsigned int length = length_left + length_right;
char* result = (char*)malloc(length);
// clear the string
memset(result, 0, length);
// copy the left part to the final string
memcpy(result, a_Left, length_left);
// append the right part the to the final string
memcpy(&result[length_left], a_Right, length_right);
// make sure the string actually ends
result[length] = 0;
return result;
}
C++:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length_left = strlen(a_Left);
unsigned int length_right = strlen(a_Right);
unsigned int length = length_left + length_right;
char* result = new char[length];
// clear the string
memset(result, 0, length);
// copy the left part to the final string
memcpy(result, a_Left, length_left);
// append the right part the to the final string
memcpy(&result[length_left], a_Right, length_right);
// make sure the string actually ends
result[length] = 0;
return result;
}
Now, let's see the sane solution:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length = strlen(a_Left) + strlen(a_Right);
char* result = new char[length];
strcpy(result, a_Left);
strcat(result, a_Right);
return result;
}
So, was this homework? I don't really care.
If it was, ask yourself: what did you learn?