1

I wrote this c++ function that reads time stamp from an online server.

I try to convert the char[] dayOfweek to String.

void printLocalTime()
{
  struct tm tm;
  if(!getLocalTime(&tm)){
    Serial.println("Failed to obtain time");
    return;
  }
 
  Serial.println(&tm, "%A, %B %d %Y %H:%M:%S");

  char dayOfweek[8];
  strftime(dayOfweek,8, "%A", &tm);

  // take dayofweek and convert in String????
}

How can i convert char[] to String?

Bolderaysky
  • 268
  • 1
  • 8
Damiano Miazzi
  • 1,514
  • 1
  • 16
  • 38
  • What is `String`? Do you mean [`std::string`](https://en.cppreference.com/w/cpp/string/basic_string), or something from non-standard library? – MikeCAT Mar 02 '23 at 10:57
  • 2
    @MikeCAT this looks like Arduino code – Alan Birtles Mar 02 '23 at 10:57
  • In your case, `dayOfweek` is already string, but c-string ( array of characters ). If you want to convert it to the std::string, then things are easy, since std::string has constructor for `char[]`. Looking at code, `Serial.println` is kind of arduino/esp stuff so it's not clear what string you want to convert it to, since on arduino there's also `String` type, which is different from `std::string` – Bolderaysky Mar 02 '23 at 11:11
  • Does this answer your question? [How to convert a char array to a string?](https://stackoverflow.com/questions/8960087/how-to-convert-a-char-array-to-a-string) – Abderrahmene Rayene Mihoub Mar 02 '23 at 11:26
  • 3
    You can just pass the character array to the constructor to create [Arduino `String`](https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/). – MikeCAT Mar 02 '23 at 11:34

2 Answers2

0

You could just utilize the + operator for strings and concatenate the characters:

// n is size of char array Arr
string temp = "";
for (int i = 0; i < n; i++) {
    temp += Arr[i];
}
// temp is now the string version of Arr

This executes in O(N) complexity.

Hudson
  • 312
  • 2
  • 18
0

"Wednesday" is a 10 characters string, by the way…
Depending on the locale you might have a problem with that.

Assuming you want a std::string:

char week_day[16] = {};
const auto k = std::strftime(week_day, 16, "%A", &tm);
if (k == 0) { /* strftime failed */ }
auto str = std::string(week_day, week_day + k);

Live on Compiler Explorer

To make an Arduino String, I believe you could replace the last line with:

auto str = String(week_day);

As long as week_day is both large enough, and zero initialized before passing it to std::strftime (so that the string is null terminated).

viraltaco_
  • 814
  • 5
  • 14