只反转字符串中的某些单词 [英] reversing only certain words of a string
问题描述
我有一个名称为"Mustang Sally Bob"的字符串
运行代码后,我希望字符串输出像这样:gnatsuM yllaS boB
我的方法是对单词进行计数,直到空格为止,然后保存该字符串在字符串中所处位置的索引.然后我要从空格开始向后打印字符.
I have a string with the name "Mustang Sally Bob"
After i run my code i want the string output to be like this: gnatsuM yllaS boB
My approach is to count the words until the space and save the index of where the space is located in the string. then Then I want to print the characters starting from the space backwards.
#include <stdio.h>
int main()
{
char* test="Mustang Sally Bob";
int length; //string length
int x;
for(length=0;test[length] !=0&&test[length];length++); //get string length
int counter;
int words = 0;
int space_index =0;
for(counter=0;counter<length;counter++) {
words++;
if(test[counter]==' ') {
space_index=counter;
for(x=space_index-1;x>=words;x--) {
printf("%c",test[x]);
}
words=0;
space_index = 0;
}
}
return 0;
}
但是当我执行此代码时,我得到的输出是yllaS g
有谁知道我为什么不能得到完整的字符串?
but when I execute this code the output I get is yllaS g
does anyone know why i cant get the full string?
推荐答案
通常,此方法不正确.
例如,任意字符串可以以空格开头.在这种情况下,将不输出前导空白.
For example an arbitrary string can start with blanks. In this case the leading blanks will not be outputted.
如果最后一个单词之后没有空格,则会将其忽略.
The last word is ignored if after it there is no blank.
变量words
不能保持单词开始的位置.
The variable words
does not keep the position where a word starts.
通过此循环计算字符串的长度
Calculating the length of a string with this loop
for(length=0;test[length] !=0&&test[length];length++);
可以写得更简单
for ( length = 0; test[length] != '\0' ; length++ );
是多余的.您始终可以依靠这样的事实,即字符串以零终止字符'\0'
终止.
is redundant. You always can rely on the fact that strings are terminated by the zero-terminating character '\0'
.
我可以提出以下解决方案
I can suggest the following solution
#include <stdio.h>
int main( void )
{
const char *test = "Mustang Sally Bob";
for ( size_t i = 0; test[i] != '\0'; )
{
while ( test[i] == ' ' ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && test[i] != ' ' ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
return 0;
}
程序输出为
gnatsuM yllaS boB
如果愿意,可以在程序后附加制表符'\t'
.在C语言中,有一个标准的C函数isblank
执行这种检查.
You could append the program with a check of the tab character '\t'
if you like. In C there is the standard C function isblank
that performs such a check.
这里是一个使用功能isblank
的演示程序.我还更改了原始字符串文字.
Here is a demonstrative program that uses the function isblank
. I also changed the original string literal.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
const char *test = " Mustang\tSally\tBob ";
puts( test );
for ( size_t i = 0; test[i] != '\0'; )
{
while ( isblank( ( unsigned char )test[i] ) ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && !isblank( ( unsigned char)test[i] ) ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
putchar( '\n' );
return 0;
}
程序输出为
Mustang Sally Bob
gnatsuM yllaS boB
这篇关于只反转字符串中的某些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!