如何使用字符串拆分数组
How to split an array using strings?
我需要编写一个程序,提示用户输入一个字符串,然后确定字符串的中间,并生成一个新字符串,交换字符串的两半,然后输出结果。
到目前为止,我有
int main(void) {
char *string = NULL;
char temp[1000];
cout << "Please enter a string" << endl;
cin.getline(temp, 999);
int length = strlen(temp);
string = new char[length];
strcpy(string,temp);
length = length / 2;
return EXIT_SUCCESS;
}
它接收字符串并存储它。我只需要一种方法将后半部分移动到一个新数组,我知道我需要使用 strcpy(),但我不知道如何正确引用数组的那部分。
由于这是C++,我将建议使用标准库算法。你要求交换序列的两半,std::rotate
就是这样做的。不幸的是,它就地进行旋转,您希望结果在不同的字符串中。
您可以复制字符串,然后进行旋转,但有一种std::rotate_copy
算法可以同时执行这两项操作(并且比单独的复制/旋转步骤更快)。
char
数组示例:
#include <algorithm>
#include <cstring>
#include <iostream>
int main()
{
char text[1000], result[1000];
std::cout << "Please enter a stringn";
std::cin.getline(text, 999);
size_t length = strlen(text);
std::rotate_copy(text, text + length / 2, text + length, result);
result[length] = ' ';
std::cout << text << 'n' << result << 'n';
}
std::string
示例:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string text, result;
std::cout << "Please enter a stringn";
std::getline(std::cin, text);
size_t length = text.size();
result.resize(length);
std::rotate_copy(text.begin(), text.begin() + length / 2, text.end(), result.begin());
std::cout << text << 'n' << result << 'n';
}
ideone.com 演示
您可以使用std::swap_ranges
但前提是两个范围的大小相同。
如果你尝试使用C,请使用strncpy。但是,我建议使用 C++ std::string
并使用std::string.substr()
和串联。后者至少对我来说会更容易。
您已经完成了解决方案的一半。在这里,我使用 strncpy 完成了它来获取前半部分,并使用指针增量来获得第二部分。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main(void)
{
char temp[1000];
cout << "Please enter a string" << endl;
cin.getline(temp, 999);
int length = strlen(temp);
char firstHalf[512];
strncpy (firstHalf, temp, length/2);
cout << "firstHalf: " << firstHalf << endl;
char* secondHalf = temp + length/2;
cout << "secondHalf: " << secondHalf << endl;
char* swapped_str = strcat(secondHalf, firstHalf);
cout << "Swapped string: " << swapped_str << endl;
return EXIT_SUCCESS;
}
std::string text(whatever...);
int sz = text.size() / 2;
for (int i = 0; i < sz; ++i)
std::swap(text[i], text[sz + i]);
当text.size()
很奇怪时,这可能会被一个关闭。
相关文章:
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 拆分字符数组并存储为向量
- 通过拆分字符数组来创建字符串
- 在C++中用字符串数组拆分声明和赋值
- 如何拆分整数并将所有内容添加到数组中?
- C++将大型数组拆分/分区为较小的数组
- 如何调试此代码以按空格将数组拆分
- 将一个std::数组拆分为一个较小大小的std::array元组
- 编辑:根据偶数和奇数元素将数组拆分为两个
- 使用提升range_iterator数组拆分字符串
- 将数组拆分为子块
- 将字符数组拆分为字母数字字符和非字母数字字符
- C++中的数组拆分
- 将字符数组拆分为字符串
- 将数组拆分为两个独立的数组
- 将字符数组拆分为两个字符数组
- 如何将字符指针数组拆分为两个带有分隔符的新字符指针数组
- 是否有STL函数将c风格的数组拆分/拼接成更小的数组?