不使用指针反向打印 C 字符串?

发布于 2024-09-14 05:11:13 字数 203 浏览 18 评论 0原文

有没有一种方法可以在不使用指针的情况下反向打印固定大小的字符串?

#include<stdio.h>

main()
{
char buffer[10];

scanf("%s", buffer);

// need to print buffer in reverse without using pointers?? 

}

Is there a way to print a string of fixed size in reverse without using pointers?

#include<stdio.h>

main()
{
char buffer[10];

scanf("%s", buffer);

// need to print buffer in reverse without using pointers?? 

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

寄离 2024-09-21 05:11:14
void outstrreverse(const char s[])
{
    size_t l=strlen(s);
    while( l && s!=&s[--l] )
        putchar(s[l]);
    if(s[0])
        putchar(s[0]);
}
void outstrreverse(const char s[])
{
    size_t l=strlen(s);
    while( l && s!=&s[--l] )
        putchar(s[l]);
    if(s[0])
        putchar(s[0]);
}
花伊自在美 2024-09-21 05:11:14

由于 C 字符串、数组和指针之间的关系,恕我直言,该练习相当简短 - C 中“字符串”最惯用的描述是由 char* 表示的,它不是数组。您的(OP)标题和帖子在字符串和字符[固定长度]之间的定义不同。

OP 应该阅读并理解此常见问题解答条目,以及在该条目和此处的帖子之间:轻松找出解决方案,并在需要时向老师/法官辩护。

我对此发表评论:永远不要使用 scanf("%s", buffer) 来填充固定长度的字符串。如果您必须使用scanf()来执行此操作,请使用字段宽度说明符:例如scanf("%9s", buffer);如果 buffer 是 [10],则您需要一个说明符 9,因为 scanf 填充缓冲区的方式:否则您必须小心龙!您还可以按字符进行 scanf 并通过循环边界来避免问题,但这可能会降低效率。

Because of the relationship between C strings, arrays, and pointers the exercise is rather shotty IMHO - the most idiomatic description of a "String" in C is represented by the char*, which is not an array. Your (the OPs) title and post differ in their definitions between string and char[fixed length].

The OP should read and understand this FAQ entry, and between that and the posts here: easily figure out a solution—as well as defend it to the teacher/judge if need be.

I'll comment on this: never use scanf("%s", buffer) to populate a fixed length string. If you must use scanf() to do it, please use a field width specifier: e.g. scanf("%9s", buffer); if buffer is an [10], you want a specifier of 9 because of how scanf fills the buffer: otherwise you must beware the dragons! You could also scanf by character and evade the issue with a loops bounds, but that would likely be less efficient.

烟火散人牵绊 2024-09-21 05:11:14
#include <stdio.h>
#include <conio.h>

void reverse(char a[], int s, int sc );

void reverse(char a[], int s, int sc ){

if ((sc-s)<(s-1))
{
a[sc-s]^=a[s-1];
a[s-1]^=a[sc-s];
a[sc-s]^=a[s-1];
reverse (a, s-1, sc) ;

}

}

void main (){


char a[]="ABCDEFG";

reverse(a, 7, 7);
printf("%d",a);
getch(); //i just use it to freeze the screen

}
#include <stdio.h>
#include <conio.h>

void reverse(char a[], int s, int sc );

void reverse(char a[], int s, int sc ){

if ((sc-s)<(s-1))
{
a[sc-s]^=a[s-1];
a[s-1]^=a[sc-s];
a[sc-s]^=a[s-1];
reverse (a, s-1, sc) ;

}

}

void main (){


char a[]="ABCDEFG";

reverse(a, 7, 7);
printf("%d",a);
getch(); //i just use it to freeze the screen

}
思念满溢 2024-09-21 05:11:13

也许有一个可爱的 K&R 函数可以在打印之前将字符串反转到位?

#include <stdio.h>
#include <string.h>

void strrev(char *s) {
  int tmp, i, j;
  for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    tmp = s[i];
    s[i] = s[j];
    s[j] = tmp;
  }
}

int main(int argc, const char *argv[]) {
  char buffer[10];
  scanf("%s", buffer);
  strrev(buffer);
  printf("%s\n", buffer);
  return 0;
}

A lovely K&R function to reverse your string in-place before printing it, perhaps?

#include <stdio.h>
#include <string.h>

void strrev(char *s) {
  int tmp, i, j;
  for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    tmp = s[i];
    s[i] = s[j];
    s[j] = tmp;
  }
}

int main(int argc, const char *argv[]) {
  char buffer[10];
  scanf("%s", buffer);
  strrev(buffer);
  printf("%s\n", buffer);
  return 0;
}
木落 2024-09-21 05:11:13
#include<stdio.h>

main()
{
  char buffer[10];

  int n = scanf("%s", buffer);

  // print the number of chars written to buffer
  if (n != EOF) {
    int len = strlen(buffer);
    if (len <= 10) {
      int i;
      for (i = len - 1; i >= 0; i--)
        printf("%c", buffer[i]);  
    } 
  }
}
#include<stdio.h>

main()
{
  char buffer[10];

  int n = scanf("%s", buffer);

  // print the number of chars written to buffer
  if (n != EOF) {
    int len = strlen(buffer);
    if (len <= 10) {
      int i;
      for (i = len - 1; i >= 0; i--)
        printf("%c", buffer[i]);  
    } 
  }
}
挖鼻大婶 2024-09-21 05:11:13

由于 [] 只是指针的语法糖,所以这里的版本完全不需要指针、数组或其他任何东西,只有一个 int。您没有说必须以某种方式存储该字符串。 :) (请注意,我使用 fgetc 而不是缓冲区和 scanf)。

[jkramer/sgi5k:.../c]# cat rev.c

#include <stdio.h>
#include <stdlib.h>

void read_print();

int main(void) {
        fputs("Enter your string, yo! ", stdout);

        read_print();

        fputs("\nDone!\n", stdout);

        return EXIT_SUCCESS;
}

void read_print() {
        int c = fgetc(stdin);

        if(c != EOF && c != '\n') {
                read_print();
                fputc(c, stdout);
        }
}
[jkramer/sgi5k:.../c]# gcc -o rev rev.c -Wall -W -Os
[jkramer/sgi5k:.../c]# ./rev 
Enter your string, yo! foobar
raboof
Done!

Since [] is just syntactic sugar for pointers, here's a version that works completely without pointers, arrays or anything else, just one single int. You didn't say that the string has to be stored somehow. :) (Note that I use fgetc instead of a buffer and scanf).

[jkramer/sgi5k:.../c]# cat rev.c

#include <stdio.h>
#include <stdlib.h>

void read_print();

int main(void) {
        fputs("Enter your string, yo! ", stdout);

        read_print();

        fputs("\nDone!\n", stdout);

        return EXIT_SUCCESS;
}

void read_print() {
        int c = fgetc(stdin);

        if(c != EOF && c != '\n') {
                read_print();
                fputc(c, stdout);
        }
}
[jkramer/sgi5k:.../c]# gcc -o rev rev.c -Wall -W -Os
[jkramer/sgi5k:.../c]# ./rev 
Enter your string, yo! foobar
raboof
Done!
╰ゝ天使的微笑 2024-09-21 05:11:13

这是一种递归方法;从技术上讲,这是使用指针,但我不会进入语言律师模式来完成如此简单的任务。

#include <stdio.h>
/* If you want it printed forward, or backward, or think of another way.. */
typedef enum {
    FRONT = 1,
    BACK,
} direction;

/* Technically still using a pointer...don't nitpick. */
void echo_string(char buffer[], size_t buflen, direction from)
{
    /* An index into the buffer to echo, which will preserve
     * its value across subsequent recursive calls.
     */
    static size_t index = 0;
    /* According to the specified direction, print from the front
     * or the back of the buffer. Advance the index (a misnomer, I guess).
     */
    if(from == FRONT) {
        printf("%c", buffer[index++]);
    }
    else {
        printf("%c", buffer[buflen - ++index]);
    }
    /* Are there any more characters to echo? Yes? Awesome! */
    if(index != buflen) {
        echo_string(buffer, buflen, from);
    }
}

int main(int argc, char **argv)
{
    char buffer[10];
    scanf("%s", buffer);
    /* Better strlen() than sizeof() here,
     * but BEWARE! scanf() is DANGEROUS!
     */
    echo_string(buffer, strlen(buffer), BACK);
    return(0);
}

Here's a recursive way of doing it; technically, this is using a pointer, but I wouldn't go into language-lawyer mode with such simple tasks.

#include <stdio.h>
/* If you want it printed forward, or backward, or think of another way.. */
typedef enum {
    FRONT = 1,
    BACK,
} direction;

/* Technically still using a pointer...don't nitpick. */
void echo_string(char buffer[], size_t buflen, direction from)
{
    /* An index into the buffer to echo, which will preserve
     * its value across subsequent recursive calls.
     */
    static size_t index = 0;
    /* According to the specified direction, print from the front
     * or the back of the buffer. Advance the index (a misnomer, I guess).
     */
    if(from == FRONT) {
        printf("%c", buffer[index++]);
    }
    else {
        printf("%c", buffer[buflen - ++index]);
    }
    /* Are there any more characters to echo? Yes? Awesome! */
    if(index != buflen) {
        echo_string(buffer, buflen, from);
    }
}

int main(int argc, char **argv)
{
    char buffer[10];
    scanf("%s", buffer);
    /* Better strlen() than sizeof() here,
     * but BEWARE! scanf() is DANGEROUS!
     */
    echo_string(buffer, strlen(buffer), BACK);
    return(0);
}
暖阳 2024-09-21 05:11:13
 reverse(char c[], int len)
 {
       if( ! (len / 2))
          return;
       char t =  c[0];   
       c[0] = c[len--];  
       c[len] = t;
       reverse(c, len-1);
 }

将错误留给学生作为练习。

 reverse(char c[], int len)
 {
       if( ! (len / 2))
          return;
       char t =  c[0];   
       c[0] = c[len--];  
       c[len] = t;
       reverse(c, len-1);
 }

The error(s) is left as an exercise to the student.

剩余の解释 2024-09-21 05:11:13

正如 caf 所指出的,我们仍在使用指针..!

这是解决问题的另一种方法(反转字符串)。
此代码片段(可能还有大多数其他代码片段)不尊重 utf8 等内容。我认为 Signines 帖子演示的 K&R 方式与我的非常接近 (:D),所以我调整了我的以适应该示例(并纠正了一些事情..)

#include <stdio.h>
#include <string.h>

void strrev(char *s) {

 size_t len = strlen(s) + 1;
 size_t i, j;

 for(i = 0; i < len / 2; i++) {

  j = len-1 - i-1;

  char tmp = s[j];
  s[j] = s[i];
  s[i] = tmp;

 }

}

int main(int argc, const char *argv[]) {
 char buffer[10];

 scanf("%s", buffer); // Look out for an overflow ;)
 strrev(buffer);
 puts(buffer);

 return(0);
}

As caf pointed out, we're still using pointers..!

Here's an other way to solve the problem (of reversing a string).
This code snippet (and probably most others) don't respect stuff like utf8. I think signines post demonstrating the K&R way was quite close to mine (:D) so I adapted mine to fit that example (and corrected some things..)

#include <stdio.h>
#include <string.h>

void strrev(char *s) {

 size_t len = strlen(s) + 1;
 size_t i, j;

 for(i = 0; i < len / 2; i++) {

  j = len-1 - i-1;

  char tmp = s[j];
  s[j] = s[i];
  s[i] = tmp;

 }

}

int main(int argc, const char *argv[]) {
 char buffer[10];

 scanf("%s", buffer); // Look out for an overflow ;)
 strrev(buffer);
 puts(buffer);

 return(0);
}
薄凉少年不暖心 2024-09-21 05:11:13

您可以使用 strrev 来反转字符串。

#include <stdio.h>
#include <string.h>

main()
{
    char buffer[10];

    scanf("%s", buffer);

    strrev(buffer);
    printf("%s", buffer);
}

You can use strrev to reverse a string.

#include <stdio.h>
#include <string.h>

main()
{
    char buffer[10];

    scanf("%s", buffer);

    strrev(buffer);
    printf("%s", buffer);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文