在 C 中操作字符串

发布于 2024-12-10 15:19:12 字数 566 浏览 1 评论 0原文

披露:这是大学的工作。我并不期望代码来完成我的任务,而是我想了解如何最好地在 C 中操作字符串。

我需要编写一个函数来以某种方式操作字符串(我不是在说什么,以确保不-其中一个提供了确切的代码)。

在 python 中,我只需执行以下操作

def foo(str):
  return str

显然事情并不像在 C 中那么容易。

任何人都可以告诉我如何最好地实现这一目标。我应该使用指针来模拟通过引用传递并只操作原始字符串吗?任何帮助/资源将不胜感激。

更新:我确实想对字符串执行操作并返回该操作的结果(也是一个字符串)。我很乐意操纵原始字符串或返回它。这将被认为是最佳实践。

我所设置的任务是基于如何执行该操作,因此我不想明确说明这一点。

所以Python将是:

def foo(str):
  #do something to str (which doesn't change it's length)
  return str

Disclosure: This is university work. I am not expecting code to accomplish my task rather I want to understand how best to manipulate strings in C.

I need to write a function to manipulate a string in a certain way (I'm not saying what so as to ensure that no-one provides exact code).

In python I'd just do the following

def foo(str):
  return str

Clearly things aren't as easy as that in C.

Can anyone tell me how best to achieve this. Should I use pointers to simulate passing by reference and just manipulate the original string? Any help / resources would be greatly appreciated.

Update: I do want to preform an operation on the string and return the result of that operation (also a string). I am happy to manipulate the original string or return it. Which ever would be considered best practice.

The task I've been set is based on how to do that operation so I didn't want to make that explicit.

So the Python would be:

def foo(str):
  #do something to str (which doesn't change it's length)
  return str

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

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

发布评论

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

评论(8

本王不退位尔等都是臣 2024-12-17 15:19:12

有两种方法:

  1. 如果您操作原始字符串,则不需要返回任何内容
  2. 如果您不想更改原始字符串,则应该使用 strdupmalloc + strcpy 复制它 并返回一个指向它的指针 (char *)。当然,调用者必须在完成后释放它。

这一切都取决于一个问题:调用者是否需要原始字符串

There are two ways:

  1. If you manipulate the original string you don't need to return anything
  2. If you don't want to change the original string you should copy it with strdup or malloc + strcpy and return a pointer (char *) to it. The caller of course must free it when done.

It all rests on the question: will the caller need the original string ?

鲸落 2024-12-17 15:19:12

有很多约定,但最常见的一个似乎是:

void foo(char *destination, const char *source);

或者

void foo(char *destination, size_t dest_len, const char *source);

因此,您将 source 中的原始字符串作为 const 传递(它不会被函数),输出字符串写入destination

当然,调用者需要确保destination有足够的大小,否则调用会导致未定义的行为。

There are many conventions, but the most common one seems to be:

void foo(char *destination, const char *source);

or

void foo(char *destination, size_t dest_len, const char *source);

So you are passing the original string in source as const (it is not going to be modified by the function), and the output string is written in destination.

Of course, the caller needs to make sure that destination is of a sufficient size, otherwise the call results in undefined behaviour.

静赏你的温柔 2024-12-17 15:19:12

这应该适用于 C:

char* foo(char *str)
{
  return str;
}

或者只是:

void foo(char *str)
{
}

因为你实际上并没有接触 str.

如果你想理解 C,并且在没有帮助的情况下完成作业,请给自己一份 K&R。立即地!

This should work in C:

char* foo(char *str)
{
  return str;
}

Or just:

void foo(char *str)
{
}

Since you aren't actually touching str.

If you want to understand C, and do your homework without help, go get yourself a copy of K&R. Immediately!

风吹雪碎 2024-12-17 15:19:12

一般来说,您的函数应该使用 malloc 分配所需大小的字符串。例如,下面是一个重复每个字符的函数:

def repeat_each(char* s) {
  char* res = malloc(strlen(s) * 2 + 1);
  if (!res) return res;
  char* resp = res;
  while (*s) {
    *resp++ = *s;
    *resp++ = *s;
    s++;
  }
  return res;
}

调用者有责任释放返回的字符串。注意不要在循环中调用strlen。如果多次需要它,请将其存储在 size_t 类型的临时变量中。

In general, your function should allocate a string of the required size with malloc. For example, here's a function that repeats each character:

def repeat_each(char* s) {
  char* res = malloc(strlen(s) * 2 + 1);
  if (!res) return res;
  char* resp = res;
  while (*s) {
    *resp++ = *s;
    *resp++ = *s;
    s++;
  }
  return res;
}

It's the callers responsibility to free the returned string. Pay attention to not call strlen in a loop. If you need it more than once, store it in a temporary variable of type size_t.

野鹿林 2024-12-17 15:19:12

如果我明白你想要什么,它会是这样的:

void foo(char *str /* , int n */) {
    // do something
    // str[3] = 'c';
}

记住你不能超过为该字符串分配的空间。因此,可以使用可选的 int 来指定长度。

这是如果您想要更改字符串但仍将其保留在原始存储中的情况。

如果您想要基于现有字符串的新字符串,那么:

char* foo(char *str /* , int n */) {
    char *ret = malloc(/* what you need */);
    // do something, probably copy str to ret
    return ret;
}

If I understand what you want, it would be something like this:

void foo(char *str /* , int n */) {
    // do something
    // str[3] = 'c';
}

Remember that you can't exceed the allocated space for that string. Hence the optional int for specifying the length.

This is if you want to change the string but still keep it in its original storage.

If you want a new string based on the existing one, then:

char* foo(char *str /* , int n */) {
    char *ret = malloc(/* what you need */);
    // do something, probably copy str to ret
    return ret;
}
烧了回忆取暖 2024-12-17 15:19:12

我认为你的问题的答案是你需要对字符串在 C 中的表示方式有一个基本的了解。一旦你明白了这一点,处理就不应该再那么困难了。

我建议阅读

http://cplus.about.com/od/learningc/ss /strings.htm

(我能想到的第一个对我来说看起来合理的网址)

祝你好运。

I think the answer to your question is that you need a fundamental understanding of how strings are represented in C. Once you got that, the processing shouldn't be that difficult anymore.

I would suggest reading

http://cplus.about.com/od/learningc/ss/strings.htm

(the first url I could come up with that looks reasonable to me)

Good luck.

春风十里 2024-12-17 15:19:12

在 C 中,您可能还需要传递可以在字符串中使用的最大大小。

char *fill_with_dots(char *data, size_t len) {
    char *dst = data;
    while (--len) *dst++ = '.';
    *dst = 0;
    return data;
}

In C you probably need to also pass the maximum size you can use in the string.

char *fill_with_dots(char *data, size_t len) {
    char *dst = data;
    while (--len) *dst++ = '.';
    *dst = 0;
    return data;
}
◇流星雨 2024-12-17 15:19:12

嗯,很难理解你所问的“操纵”可能意味着很多。

如果您不想保留原始内容,那么您可以将函数定义如下:

void changeString(char* str);

如果您需要保留原始内容,那么您可能需要将内容复制到临时缓冲区,更改它并返回它,如下所示:

char* returnModified(char* str )
{
      char* tmp = malloc(strlen(str));
      strcpy(tmp, str);
      // do watever
      return tmp;
}

使用最新的方法确保正确跟踪分配的内存

Well, it's hard to understand what you ask as "manipulating" can mean a lot.

If you don't want to keep the original then you could define the function as following:

void changeString(char* str);

if you need to keep the original then you might want to copy the contents to a temporary buffer, change it and return it like this:

char* returnModified(char* str )
{
      char* tmp = malloc(strlen(str));
      strcpy(tmp, str);
      // do watever
      return tmp;
}

With the latest approach make sure you keep track of the allocated memory properly

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