如何使用字符串拆分数组

How to split an array using strings?

本文关键字:数组 拆分 字符串 何使用      更新时间:2023-10-16

我需要编写一个程序,提示用户输入一个字符串,然后确定字符串的中间,并生成一个新字符串,交换字符串的两半,然后输出结果。

到目前为止,我有

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()很奇怪时,这可能会被一个关闭。