[英]Reverse a string without strtok in C
Working on a program that uses RPN (Reverse Polish Notation).处理使用 RPN(逆波兰表示法)的程序。
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).我有一个函数可以在不使用strtok
或触发printf
情况下反转字符串的所有单词(与在线和此处找到的所有解决方案不同)。
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;
}
}
And then it's called in main like this:然后像这样在 main 中调用它:
char s[MAX] = "5 60 +";
while(s != NULL){
printf("%s\n", extract(s));
}
The output is + 60
with the cursor endessly waiting for something but the expected output should be + 60 5
输出为+ 60
,光标无休止地等待某事,但预期输出应为+ 60 5
A standard approach is to reverse each word within a string and then to reverse the whole string.标准方法是反转字符串中的每个单词,然后反转整个字符串。
Here you are.这个给你。
#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;
}
The program output is程序输出是
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;
}
The program output is程序输出是
" 5 60 +"
" + 60 5"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.