2

which method c do this? thanks

for example, a string [] = "abc";

a array[4];

array[0] = 'a';
array[1] = 'b';
array[2] = 'c';

thanks

6 Answers 6

3

Why don't you just subscript it...

int main() {

  char *str = "hello";

  printf("%c", str[0]); // h

  return 0;
}

CodePad.

You can also use array syntax to define the string char str[] = "hello".

Update

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

int main() {

  char str[] = "hello";
  int i;
  int strLength = strlen(str);

  for (i = 0; i < strLength; i++) {

      printf("[%c]", str[i]);

  }

  return 0;
}

Output

[h][e][l][l][o]

CodePad.

Sign up to request clarification or add additional context in comments.

2 Comments

#import? ?? And you need to #include <stdio.h> too for printf prototype.
@pmg Whoops, been a while since I used C. Will revise, thanks.
2

A string in C is actually an array of characters so you don't have to do anything.

retrieve it like so


char *string = "abcdef";
for (int i = 0; i < 7; ++i) {
    printf("%c\n", string[i]);
}

1 Comment

There's no C++ tag here so please don't post C++ code as an answer.
1

Try this:

char variable[] = "abc";

Comments

0

Consider using the function memcpy.

Comments

0

In C you don't have any specific type for string. String is a char * and points to the start of the string. Each string ends with a null character. So, you can directly use your string (char *) variable as an array but stop one character short of its strlen

Comments

0

A string in C is itself an array use the following:

char yourarray[] = "asldkjsl";

each character is an array you can access them as yourarray[0], yourarray[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.