gpt4 book ai didi

c++ - 使用指针从 char array[] 中移除/删除字符

转载 作者:行者123 更新时间:2023-11-30 01:10:08 25 4
gpt4 key购买 nike

我需要帮助从 char 数组中删除空格和特殊字符。我一直遇到的问题是删除函数只适用于字符串数据类型,如果我没记错的话。赋值需要一个 char 数组而不是一个字符串,所以我不能只转换它或有一个字符串变量。我试过查找它,但一切都只是建议将其转换为字符串或以字符串开始,我做不到。我是编程新手,指针对我来说有点奇怪,所以如果答案很明显,我很抱歉。

    #include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <ctype.h>
using namespace std;

int main()
{
const int SIZE = 80;
char str[SIZE];
char* strPtr;
int strlength;
int j = 0;
int front = 0, back; int flag = 1;

strPtr = str;

cout << "This program checks for palidromes." << endl;
cout << "Please enter a phrase." << endl;
cout << endl;
cin.getline(str, SIZE);

//Get the length of string str

strlength = strlen(str);

//Convert all the characters in the string str to uppercase
for (int i = 0; i < strlength; i++)
{
if (!isupper(str[i]))
str[i] = toupper(str[i]);
}

//Remove all the special characters except letters a - z
for (int i = 0; i < strlength; i++)

if (!isalpha(str[i])||(!isalnum(str[i])))
{
str.erase(str[i]); // need help here. Not sure how to go about it.
}

//str[j] = '\0';

return 0;
}

最佳答案

char* tail = std::remove_if(str, str + strlength,
[](char c){ return !isalpha(c)||(!isalnum(c)); });
strlength = tail - str;
*tail = 0;

关于c++ - 使用指针从 char array[] 中移除/删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38819995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com