如何为字符串分配一个从数组中间开始的char数组
How to assign string a char array that starts from the middle of the array?
例如,在以下代码中:
char name[20] = "James Johnson";
我想把空白之后开始的所有字符都分配给char数组的末尾,所以基本上字符串如下:(不是初始化它,只是展示想法)
string s = "Johnson";
因此,从本质上讲,字符串将只接受姓氏。我该怎么做?
我想你想要这样。。
string s="";
for(int i=strlen(name)-1;i>=0;i--)
{
if(name[i]==' ')break;
else s+=name[i];
}
reverse(s.begin(),s.end());
需要
include<algorithm>
总有不止一种方法可以做到这一点——这取决于你的要求。
你可以:
- 搜索第一个空间的位置,然后将char*指向该位置之后的一个(在<cstring>中查找strchr)
- 将字符串拆分为子字符串列表,其中拆分的字符是一个空格(查找strtok或boost split)
std::string
有一整套用于字符串操作的函数,我建议您使用这些函数。
您可以使用std::string::find_first_of
找到第一个空白字符,并从中拆分字符串:
char name[20] = "James Johnson";
// Convert whole name to string
std::string wholeName(name);
// Create a new string from the whole name starting from one character past the first whitespace
std::string lastName(wholeName, wholeName.find_first_of(' ') + 1);
std::cout << lastName << std::endl;
如果你担心多个名字,你也可以使用std::string::find_last_of
如果你担心名字之间没有空格,你可以使用std::string::find_first_not_of
搜索字母表中的字母。链接中给出的示例是:
std::string str ("look for non-alphabetic characters...");
std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
if (found!=std::string::npos)
{
std::cout << "The first non-alphabetic character is " << str[found];
std::cout << " at position " << found << 'n';
}