String to const char* in Arduino?

2019-07-18 15:16发布

I have a variable tweet that is a string and it has a character at the very beginning that I want to clip off.

So what I want to do is use strstr() to remove it. Here's my code:

tweet = strstr(tweet, "]");

However, I get this error:

cannot convert 'String' to 'const char*' for argument '1' to 
'char' strstr(const char*, const char*)

So my thought would be to convert tweet into a char. How would I go about doing so?

6条回答
Evening l夕情丶
2楼-- · 2019-07-18 15:27

I realize this is an old question, but if you're trying to, say, compare a specific char, and not just one letter in a string, then what you want is string.charAt(n). For example, if you're doing serial programming and you need to check for STX (\02) than you can use the following code.

char STX = '\02'

if (inputString.charAt(0) == STX) {
  doSomething();
}
查看更多
Melony?
3楼-- · 2019-07-18 15:41

Using the following statement tweet.c_str() will return the string buffer, which will allow you to perform the edit you want.

查看更多
仙女界的扛把子
4楼-- · 2019-07-18 15:43

you can do that easier. Since you're using C++:

tweet = tweet.substring(1);

substr() returns a part of the string back to you, as string. The parameter is the starting point of this sub string. Since string index is 0-based, 1 should clip off the first character.

If you want to use strstr you can just cast tweet into a c-string:

tweet = strstr( tweet.c_str(), "]" );

However, that's pretty inefficient since it returns a c-string which has to be turned into a std::string against in order to fit into tweet.

查看更多
家丑人穷心不美
5楼-- · 2019-07-18 15:45

How about you use substring instead. This will be less confusing than converting between different types of string.

http://arduino.cc/en/Reference/StringSubstring

查看更多
爷、活的狠高调
6楼-- · 2019-07-18 15:50

string has a c_str() member function that returns const char *.

查看更多
时光不老,我们不散
7楼-- · 2019-07-18 15:51

Look at:

string.indexOf(val)
string.indexOf(val, from)

Parameters

string: a variable of type String
val: the value to search for - char or String
from: the index to start the search from

See this page

查看更多
登录 后发表回答