有没有类似于 C 中 Java 的字符串 'charAt()' 方法的东西?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35109476/
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
is there anything similar to Java's string 'charAt()' Method in C?
提问by ekeith
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.
我正在尝试将一段代码从 Java 转换为 C,但我被困在这里,试图在每个位置获取一个字符。
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?
C 中有没有类似的东西可以将行ch = line.charAt(pos)
从 java转换为 C?
采纳答案by user3629249
in C, the easiest way to get a char from an array of character (I.E. a string)
在 C 中,从字符数组(即字符串)中获取字符的最简单方法
given the variables in your posted code,
鉴于您发布的代码中的变量,
char ch;
line += ' ';
while (pos < line.length())
{
ch = line.charAt(pos);
...
- assuming that the string is terminated with a NUL byte ('\0')
- assuming there is room in the
line[]
array for another character
- 假设字符串以 NUL 字节 ('\0') 结尾
- 假设
line[]
数组中有另一个字符的空间
would become:
会成为:
#include <string.h>
strcat( line, " ");
size_t maxPos = strlen( line );
for( pos = 0; pos < maxPos; pos++ )
{
ch = line[pos];
....
回答by DominicEU
You can access the values as though the String was an array.
您可以访问这些值,就像 String 是一个数组一样。
char str[] = "Hello World";
printf("%c", str[0]);
回答by Faraz
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
来源:这里