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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2114377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:13:10  来源:igfitidea点击:

Strings in C, how to get subString

c

提问by SuperString

I have a string:

我有一个字符串:

char * someString;

If I want the first five letters of this string and want to set it to otherString, how would I do it?

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

回答by pib

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '
char* someString = "abcdedgh";
char* otherString = 0;

otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;
'; // place the null terminator

回答by Liao

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

UPDATE:
Tip:A good way to understand definitions is called the right-left rule (some links at the end):

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

Start reading from identifier and say aloud => "someStringis..."
Now go to right of someString (statement has ended with a semicolon, nothing to say).
Now go left of identifier (*is encountered) => so say "...a pointer to...".
Now go to left of "*" (the keyword charis found) => say "..char".
Done!

从标识符开始阅读并大声说 => " someStringis..."
现在转到 someString 的右侧(语句以分号结束,没什么好说的)。
现在转到标识符的左侧(*遇到)=> 所以说“...指向...的指针”。
现在转到“ *”的左侧(char找到关键字)=> 说“..char”。
完毕!

So char* someString;=> "someString is a pointer to char".

所以char* someString;=> “someString 是一个指向 char 的指针”。

Since a pointer simply points to a certain memory address, it can also be used as the "starting point" for an "array" of characters.

由于指针只是指向某个内存地址,因此它也可以用作字符“数组”的“起点”。

That works with anything .. give it a go:

这适用于任何事情..试一试:

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);
}

Some links: How to interpret complex C/C++ declarationsand How To Read C Declarations

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

回答by Dan Olson

Generalized:

概括:

char *subString(char *someString, int n) 
{
   char *new = malloc(sizeof(char)*n+1);
   strncpy(new, someString, n);
   new[n] = '
#include <stdio.h>

int main()
{
    const char source[] = "This is a string array";
    char dest[17];

    // get first 16 characters using precision
    snprintf(dest, sizeof(dest), "%.16s", source);

    // print substring
    puts(dest);
} // end main
'; return new; }

回答by Neal

You'll need to allocate memory for the new string otherString. In general for a substring of length n, something like this may work for you (don't forget to do bounds checking...)

您需要为新字符串otherString 分配内存。一般来说,对于长度为 n 的子字符串,这样的事情可能对你有用(不要忘记做边界检查......)

#include <stdio.h>

printf( "SUBSTR: %s", substr("HELLO WORLD!",2,5) );

This will return a substring of the first n characters of someString. Make sure you free the memory when you are done with it using free().

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

回答by angelvmx

You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":

您可以使用 snprintf 精确获取字符数组的子字符串。这是一个名为“substring.c”的文件示例:

#include <stdlib.h>

char *substr(char *s, int a, int b) {
    char *r = (char*)malloc(b);
    strcpy(r, "");
    int m=0, n=0;
    while(s[n]!='
char str[10];
') { if ( n>=a && m<b ){ r[m] = s[n]; m++; } n++; } r[m]='
char str1[24] = "This is a simple string.";
char str2[6];
strncpy(str1 + 10, str2,6);
'; return r; }

Output:

输出:

This is a string

这是一个字符串

Note:

笔记:

For further information see printf man page.

有关更多信息,请参见 printf 手册页。

回答by Daniel J.

This code is substrfunction that mimics function of same name present in other languages, just parse: string, start and number of characters like:

此代码是substr函数,它模仿其他语言中存在的同名函数,只需解析:字符串、开头和字符数,例如:

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

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

The above will print HELLO. If you pass a value over the string length, it will be silently ignored, as the loop only iterates the length of the string.

以上将打印 HELLO。如果您在字符串长度上传递一个值,它将被静默忽略,因为循环只迭代字符串的长度。

char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;

回答by calvinjarrod

You can treat C strings like pointers. So when you declare:

您可以将 C 字符串视为指针。所以当你声明:

char largeSrt[] = "123456789-123";  // original string

char * substr;
substr = strchr(largeSrt, '-');     // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size) 

char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength);  // copy only 9 characters 
newStr[substringLength] = '##代码##'; // close the new string with final character

printf("newStr=%s\n", newStr);

free(newStr);   // you free the memory 

strcan be used as a pointer. So if you want to copy just a portion of the string you can use:

str可以用作指针。因此,如果您只想复制字符串的一部分,您可以使用:

##代码##

This will copy 6 characters from the str1array into str2starting at the 11th element.

这将从第 11 个元素开始将 6 个字符从str1数组复制到str2 中

回答by gavaletz

##代码##

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.

如果您不使用 printf 语句并且在所有程序中都放置常量,除了最小的程序是不好的形式,应该避免使用 stdio.h。

回答by Steve Emmerson

Doing it all in two fell swoops:

一举两得:

##代码##

回答by Cristian

##代码##