c - 编辑字符串而不更改非字母字符
问题描述
我需要制作一个像这样编辑命令行参数的程序:
- 将每个单词的第一个字母移动到单词的末尾,并将其变为小写
- 检查原始的第一个是否较低/较高并使新的第一个相同
- 将“o”添加到长度 < 3 的每个单词,并将“an”添加到其他单词
- 每个非 isalpha 字符保持不变
- 当有空格或 nonisalpha char 时,单词被认为是分开的
我有一些代码,但我的问题是我不知道如何在不修改它们的情况下保留字符串上的非 isalpha 字符。这是代码:
/*Example:
I *REALLY* like Yale's course-selection procedures.
to
Ian *EALLYro* ikelo Aleyo'san ourseco-electionso rocedurespo.
*/
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("\nNot enough arguments! Press any key to exit.\n");
system("pause");
exit(0);
}
// copies the arguments to a string
char src[100] = {0};
for(int i = 1; i <= argc-1; i++)
{
strcat(src, argv[i]);
strcat(src, " ");
}
printf("\nInput is:\n%s\n", src);
// divides the main string in substrings when there is a space
int k = 0, j = 0, m = 0, pos[50];
char ans[100][100] = {0};
// saves the position of the nonalpha characters
for(int i = 0; i <= strlen(src); i++)
{
if(isalpha(src[i]) == 0 && isspace(src[i]) == 0)
{
pos[m] = i;
m++;
}
}
for(int i = 0; i <= strlen(src); i++)
{
if(src[i] == ' ' || src[i] == '\0' || isalpha(src[i]) == 0)
{
ans[k][j] = '\0';
k++; //for next word
j = 0; //for next word, init index to 0
}
else
{
ans[k][j] = src[i];
j++;
}
}
printf("\nOutput is: \n");
for(int i = 0; i < k; i++)
{
processword(ans[i]); // edits the words
printf("%s ", ans[i]);
}
printf("\n\n");
system("pause");
return 0;
}
这就是我编辑单词的方式:
char* processword(char* word)
{
if(strlen(word) == 0)
{
return NULL;
}
char first = word[0]; // saves first letter
for (int i = 0; i <= strlen(word); i++) // moves everything back one space
{
word[i-1] = word[i];
}
word[strlen(word)] = tolower(first); // moves first to end
if (isupper(first) > 0) // checks if the original first was uppercase, to make the new first the same
{
word[0] = toupper(word[0]);
}
// ads the suffix
if(strlen(word) <= 3)
{
strcat(word, "an");
}
else
{
strcat(word, "o");
}
return word;
}
解决方案
推荐阅读
- asp.net - 回发后列表项消失
- neo4j - 在 Neo4j 中重新加载电影推荐数据集
- flutter - 颤振下拉按钮
- java - Java Apache Http 客户端 - 仅通过 HTTPS 删除标头中的下划线
- angular - Npm 链接:找不到库的模块
- python - 使用 Python / Pandas 复制 Microsoft Excel 的数据栏渐变条件格式
- javascript - 如何在.Net aspx页面中添加反应组件
- ios - iOS - 应用程序未运行时向服务器发送纬度和经度(应用程序处于暂停状态)
- javascript - 将数据插入数据表角度时出错
- java - 在 glTexImage2D() 中指定 GL_RGBA32F 时输出奇怪