저는 '주마'라는 프로그램을 쓰고 있습니다. 이 프로그램은 다음과 같이 작동합니다.C/C++에서 문자열을 char 배열로 수정하는 방법은 무엇입니까?
Input:
ACCBA // a string make up of char from 'A' to 'Z'
5 // number of inputs
1 B // insert char 'B' to position '1' of the string
0 A // and so on...
2 B
4 C
0 A
3 개의 동일한 문자가 서로 옆에있을 때 문자열에서 지우거나 삭제하거나 삭제합니다.
예를 들어 문자열 'ABCC'의 위치 2에 'C'문자를 삽입하면 'CCC'가 문자열에서 제거되므로 'AB'가 표시됩니다.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void append (char subject[], const char insert[], int pos) {
char buf[100] = {};
strncpy(buf, subject, pos);
int len = strlen(buf);
strcpy(buf+len, insert);
len += strlen(insert);
strcpy(buf+len, subject+pos);
strcpy(subject, buf);
}
int main()
{
int n, pos;
int k = 0;
int length = 0;
char zuma[100], marble[100];
scanf("%s", zuma);
scanf("%d", &n);
for (int i = 0; i < n; ++i)
{
scanf("%d %s", &pos, marble);
append(zuma, marble, pos); // acts like string::insert
length = strlen(zuma);
while (k != length && length >= 3)
{
if (zuma[k] == zuma[k + 1] && zuma[k] == zuma[k + 2])
{
//zuma.erase(k, 3); // need help with this part to remove 3 same chars like string::erase
k = 0;
}
else
k++;
}
if (strlen(zuma) != 0)
{
printf("%s\n", zuma);
k = 0;
}
else
printf("%s\n","-");
}
return 0;
}
내 문제는 3 개 같은 문자를 바로 제거하는 함수를 작성하는 방법입니다 : 이것은 문자 배열 내 코드가
#include <iostream>
using namespace std;
int main()
{
int n, pos;
int k = 0;
int length = 0;
string zuma, marble; // i use string
cin >> zuma;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> pos >> marble;
zuma.insert(pos, marble);
length = zuma.length(); // length of current string
// compare each char from pos[i] with pos[i+1] and pos[i+2]
// and then ++i until end of string
while (k != length && length >= 3)
{
if (zuma[k] == zuma[k + 1] && zuma[k] == zuma[k + 2])
{
zuma.erase(k, 3); // erase 3 same char in the string
k = 0; // set k to zero to start from pos[0] again
}
else
k++;
}
// if string is not empty
if (!zuma.empty())
{
cout << zuma << endl; // output the current char in the string
k = 0;
}
else
cout << "-" << endl;
}
return 0;
}
입니다 :
Output:
ABCCBA
AABCCBA
AABBCCBA // the process is AABBCCCBA -> AABBBA -> AAA -> -
- // if the string is empty, we output "-"
A
이 문자열 내 코드입니다 like string :: erase는 무엇을합니까?
도움 주셔서 감사합니다.
명확한 설명 : 문자열을 통해 더 명확하고 안전하고 간결한 방식으로 수행 할 수있는 작업을 char 배열과 함께 사용하고 싶습니까? 그런데, if 절이 문자열의 길이를 넘어서는 문자에 접근하기 때문에'k'가'length() - 2'에 도달하면 문자열 솔루션이 충돌 할 가능성이 높습니다. – Kolja
@Kolja 그렇습니다. scanf가 문자열에 문제가있는 것처럼 char 배열을 사용하고 싶습니다. 내 친구가 scanf가 cin보다 빠르다고 말했기 때문에 내가 잘못하면 corrent를 사용합니다. – warofglory
C++로 작업하는 경우 C 함수를 사용하는 것이 좋은 이유라고 생각하지 않습니다. 실제로 속도 차이가 있다면 (가능하다면), 단지 몇 문자 (사용자 입력의 경우 CPU주기에서 측정 한 것보다 훨씬 지연 시간이 길어집니다. 사용자를 기다리는 중)? 'std :: cin'을 찾으십시오. 나중에 필요할 때마다 문자열로 교체 할 수도 있습니다. 여전히'scanf'를 사용하고 싶다면, Wimmel의 대답을보십시오, 당신이 원하는 것을합니다. – Kolja