简体   繁体   中英

is there anything similar to Java's string 'charAt()' Method in C?

I'm trying to convert a piece of code from Java to C and I got stuck here, trying to get a character at each position.

char ch;

line += ' ';
    while (pos < line.length()) 
    {
      ch = line.charAt(pos);  
...

is there anything similar in C to convert the line ch = line.charAt(pos) from java to C?

You can access the values as though the String was an array.

char str[] = "Hello World";
printf("%c", str[0]);

You can get a character at specific position in this way

char str[] = "Anything";
printf("%c", str[0]);

but when you have a pointer array:

char* an_array_of_strings[]={"balloon", "whatever", "isnext"};
cout << an_array_of_strings[1][2] << endl;

If you need to change the strings use

char an_array_of_strings[][20]={"balloon", "whatever", "isnext"};
cout << an_array_of_strings[1][2] << endl;

source: here

in C, the easiest way to get a char from an array of character (IE a string)

given the variables in your posted code,

char ch;

line += ' ';
while (pos < line.length()) 
{
    ch = line.charAt(pos);  
...
  1. assuming that the string is terminated with a NUL byte ('\\0')
  2. assuming there is room in the line[] array for another character

would become:

#include <string.h>
strcat( line, " ");
size_t maxPos = strlen( line );
for( pos = 0; pos < maxPos; pos++ )
{
    ch = line[pos];
....

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