C++ 如何将字符串拆分为单个字符

c++ how to split a string into single characters

本文关键字:单个 字符 拆分 字符串 C++      更新时间:2023-10-16

我已经有了这个

std::string str_1, str_2, str_3, str_4, str_5, str_6, str_7, str_8;
std::string str;
std::getline(std::cin,str);
std::istringstream iss(str);
iss >> str_1 >> str_2 >> str_3 >> str_4 >> str_5 >> str_6 >> str_7 >> str_8;

输入:H E L L O (在一个字符串中(

输出:str_1 =H str_2 =E str_3=L str_4=L str_5=O

这就是我试图实现的目标

输入:你好(在单个字符串中使用 CIN (

输出: h e l l o (在 5 个单独的字符串中(

我需要输入在一个字符串中,因为用户输入的字符数各不相同

cin >> str_1 >> str_2 >> str_3 >> str_4 >> str_5 >> str_6 >> str_7 >> str_8 >> endl;

不起作用,因为您必须声明所有变量

为什么不直接迭代一个字符串并像这样打印它呢?

string str1;
cin >> str1;
for(int i=0; i<str1.length(); i++)
cout << str[i] << " ";
cout << endl;
string a = "hello"; 
cout << a[1];

尝试遍历 a[对于不同的值]

#include <iostream>
#include <string.h>
using namespace std;
typedef struct _ARRAY_ITEMS
{
char item[10];
int iPosicion;
} ARRAY_ITEMS;

int tokens(char * string, char token, ARRAY_ITEMS * outItems){
char cItem[50];
char TempItem[50];
int x = 0,i;
ARRAY_ITEMS items;
memset(cItem, 0x00, sizeof(cItem));
memset(TempItem, 0x00, sizeof(TempItem));
sprintf( cItem,"%s", string);
for(i = 0; i <= strlen(cItem); i++){
if (cItem[i] != token){
sprintf( TempItem,"%s%c",TempItem, cItem[i]);
}else{
memset( &items, 0x00, sizeof( ARRAY_ITEMS ) );
sprintf( items.item,"%s",TempItem);
items.iPosicion = x;
memcpy( &outItems[x], &items, sizeof( ARRAY_ITEMS ) );
memset(TempItem, 0x00, sizeof(TempItem));
x++;
}
}
memset( &items, 0x00, sizeof( ARRAY_ITEMS ) );
sprintf( items.item,"%s",TempItem);
items.iPosicion = x;
memcpy( &outItems[x], &items, sizeof( ARRAY_ITEMS ) );
return x;
}
int main() {
ARRAY_ITEMS items[10];
int iLenPos = 0;
// iLenPos = tokens("01x02x03",'x', items);  //split for ","
// iLenPos = tokens("01,02,03",',', items); //split for ","
iLenPos = tokens("01.02.03",'.', items);  //split for "."
for ( int i = 0; i <= iLenPos; ++i)
{
printf("POSICION %d numero %sn",items[i].iPosicion, items[i].item);
}
//print POSICION 0 numero 01
//print POSICION 1 numero 02
//print POSICION 2 numero 03
return 0;
}