C语言中的字符串,如何获取subString

Sup*_*ing 48 c

我有一个字符串:

char * someString;
Run Code Online (Sandbox Code Playgroud)

如果我想要这个字符串的前五个字母并想要设置它otherString,我该怎么做?

pib*_*pib 53

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator
Run Code Online (Sandbox Code Playgroud)

  • @pib:otherString [5] ='\ 0'; (4认同)
  • 或者`otherString [5] =(char)0;`如果你想对它挑剔.Char是一个整数类型,因此编译器不会(或不应该)抱怨只是为它分配一个原始整数. (4认同)
  • 感谢您提醒我将终止字符放在双引号的单引号中。 (2认同)
  • @pib 不清楚[评论](/sf/ask/148006421/#comment2066644_2114388)。C 语言中的“otherString[5] = '\0';”和“otherString[5] = 0;”都将值为 0 的“int”分配给“char”。那么 `(char)` 在 `otherString[5] = (char)0;` 中有何帮助? (2认同)
  • 这是个糟糕的建议。`strncpy` 是一个危险的函数,永远不应该使用,因为太多人无法理解它是如何工作的。在这种情况下,“strncpy”可能会也可能不会自行终止字符串,具体取决于长度。它变化无常、不可靠,而且最初根本不打算与以 null 结尾的字符串一起使用。请参阅[strcpy 危险吗?应该使用什么代替?](https://software.codidact.com/posts/281518) (2认同)

Lia*_*iao 7

char* someString = "abcdedgh";
char* otherString = 0;

otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;
Run Code Online (Sandbox Code Playgroud)

更新:
提示:理解定义的一种好方法称为左右规则(最后的一些链接):

从标识符开始读取并大声说出=>" someString是......"
现在转到someString的右边(语句以分号结束,没什么好说的).
现在左边的标识符(*遇到)=>所以说"......指向......".
现在转到左边的" *"(char找到关键字)=>说"..char".
完成!

所以char* someString;=>"someString是指向char的指针".

由于指针只是指向某个存储器地址,因此它也可以用作字符"数组"的"起始点".

这适用于任何事情..放手一搏:

char* s[2]; //=> s is an array of two pointers to char
char** someThing; //=> someThing is a pointer to a pointer to char.
//Note: We look in the brackets first, and then move outward
char (* s)[2]; //=> s is a pointer to an array of two char
Run Code Online (Sandbox Code Playgroud)

一些链接: 如何解释复杂的C/C++声明如何读取C声明


Dan*_*son 7

广义:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果在dest [len + 1]不加'\ 0'会更好吗? (2认同)

Nea*_*eal 5

您需要为新字符串otherString分配内存。通常,对于长度为n的子字符串,类似这样的方法可能对您有用(不要忘记进行边界检查...)

char *subString(char *someString, int n) 
{
   char *new = malloc(sizeof(char)*n+1);
   strncpy(new, someString, n);
   new[n] = '\0';
   return new;
}
Run Code Online (Sandbox Code Playgroud)

这将返回someString的前n个字符的子字符串。完成使用free()的操作后,请确保释放内存。