简体   繁体   中英

How I can read characters of a string?

I've a question, let's consider I've an array, char A[50] . Let's say, containing "abcdef" .

How I can read characters, let's say "cd" and save in another array, char B[50] ?

You can use strncpy to copy a substring from one array to another, and then terminate that substring:

int start = 2, count = 2
strncpy(B, A + start, count);
B[count] = '\0';

Answer to an older version of the question that was about C++:

However, there is a better approach: Don't use arrays, but std::string instead:

std::string A = "abcdef";
auto B = A.substr(2, 2);

If you want to use addresses and offsets you could just use sprintf such as:

#include <stdio.h>

int main()
{
  char A[50] = "abcdef";
  char B[50] = {0};

  unsigned offset = 2;
  unsigned len    = 2;

  sprintf(B,"%.*s",len,&A[offset]);
  printf("%s",B);
  return(0);
}

This will result in filling B with the values of A[2] and A[3] and a string terminator = "cd\\0". If you don't want strings, but just the data in the elements of the array, then a simple memcpy() will do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM