我正在尝试将一段代码从Java转换为C并且我被困在这里,试图在每个位置获得一个角色。
char ch;
line += ' ';
while (pos < line.length())
{
ch = line.charAt(pos);
...
C中有什么类似的东西可以将行ch = line.charAt(pos)
从java转换为C吗?
答案 0 :(得分:1)
您可以像使用String一样访问值。
public class Logic {
private int position = 1;
public void appendPosition(){
// When debugging strange stuff,
// keep each step simple.
// Is calculatePosition working as it should?
int newPosition = calculatePosition(this.position);
this.position = newPosition;
}
// Always use parameters as final. It's good karma.
// You don't NEED to declare them as final,
// but let's try to be EXTRA clear.
private int calculatePosition(final int targetPosition){
// Yes, make as much as you can immutable
// You'll save a ton of mental bandwidth.
final int localCopy = targetPosition +6;
if(snakeLocations[localCopy]>0) {
return (localCopy -6);
// Don't force the maintenance programmer to
// read all your stuff. Return often, return early.
// This isn't Cc++, where you need to
// actually free your reference/pointers,
// so there's no point enforcing a single return.
}
if(ladderLocations[localCopy]>0) {
return (localCopy+6);
}
return localCopy;
}
}
答案 1 :(得分:1)
你可以通过这种方式获得特定位置的角色
What file would you like to count the lines of code for?
Counting lines in test1.txt...
// This comment should not count
This file now has two lines of code
// Another comment that shouldn't be counted
}
A total of 4 lines should be counted.
3
但是当你有一个指针数组时:
char str[] = "Anything";
printf("%c", str[0]);
如果您需要更改字符串,请使用
char* an_array_of_strings[]={"balloon", "whatever", "isnext"};
cout << an_array_of_strings[1][2] << endl;
来源:here
答案 2 :(得分:0)
在C中,从字符数组中获取字符的最简单方法(I.E. a string)
根据您发布的代码中的变量,
char ch;
line += ' ';
while (pos < line.length())
{
ch = line.charAt(pos);
...
line[]
数组中有另一个角色的空间会变成:
#include <string.h>
strcat( line, " ");
size_t maxPos = strlen( line );
for( pos = 0; pos < maxPos; pos++ )
{
ch = line[pos];
....