反转C中没有strtok的字符串 [英] Reverse a string without strtok in C
问题描述
正在开发使用RPN(反向波兰表示法)的程序.
Working on a program that uses RPN (Reverse Polish Notation).
我有一个函数,可以在不使用 strtok
或触发 printf
的情况下反转字符串的所有单词(与在线和此处找到的所有解决方案不同).
I have a function that reverses all the words of string without using strtok
or triggering printf
(unlike all the solutions found online and here).
该函数实际上会部分起作用,因为它会打印给定字符串中除最后一个字符串以外的所有单词,我需要帮助找出正在发生的事情.
The function actually works partially as it prints all the words of a given string except the last one and I need help figuring out what's going on.
char *extract(char s[]) {
if (s[0] == '\0')
return NULL;
int i = 0;
char *p = NULL;
while (s[i] != '\0') {
if (s[i] == ' ')
p = s + i;
i++;
}
if (p != NULL) {
*p = '\0';
return p + 1;
}
}
然后在main中这样调用它:
And then it's called in main like this:
char s[MAX] = "5 60 +";
while(s != NULL){
printf("%s\n", extract(s));
}
输出为 + 60
,光标最终等待某事但预期输出应为 + 60 5
The output is + 60
with the cursor endessly waiting for something
but the expected output should be + 60 5
推荐答案
一种标准方法是反转字符串中的每个单词,然后反转整个字符串.
A standard approach is to reverse each word within a string and then to reverse the whole string.
您在这里.
#include <stdio.h>
#include <string.h>
static char * reverse( char *s, size_t n )
{
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[ i ];
s[ i ] = s[ n - i - 1 ];
s[ n - i - 1 ] = c;
}
return s;
}
char * reverse_by_words( char *s )
{
const char *delim = " \t";
char *p = s;
while ( *p )
{
p += strspn( p, delim );
if ( *p )
{
char *q = p;
p += strcspn( p, delim );
reverse( q, p - q );
}
}
return reverse( s, p - s );
}
int main(void)
{
char s[] = "5 60 +";
puts( s );
puts( reverse_by_words( s ) );
return 0;
}
程序输出为
5 60 +
+ 60 5
如果您想保持前导空格和尾随空格在原始字符串中的位置,则函数可以采用以下方式
If you want to keep leading and trailing spaces as they were in the original string then the functions can look the following way
#include <stdio.h>
#include <string.h>
static char *reverse( char *s, size_t n )
{
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i -1 ];
s[n - i - 1] = c;
}
return s;
}
char * reverse_by_words( char *s )
{
const char *delim = " \t";
char *first = s, *last = s;
for ( char *p = s; *p; )
{
p += strspn( p, delim );
if ( last == s ) first = last = p;
if ( *p )
{
char *q = p;
p += strcspn( p, delim );
last = p;
reverse( q, p - q );
}
}
reverse( first, last - first );
return s;
}
int main(void)
{
char s[] = "\t\t\t5 60 +";
printf( "\"%s\"\n", s );
printf( "\"%s\"\n", reverse_by_words( s ) );
return 0;
}
程序输出为
" 5 60 +"
" + 60 5"
这篇关于反转C中没有strtok的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!