我是 C 的新手,作为我任务的一部分,我必须使用 fgets() 删除添加在字符串末尾的换行符。
我的讲师建议使用这种方法:
char names[20];
fgets(names,20,fp);
names[strlen(names)-1]='\0';
我省略了一些代码,因为我只是在演示方法。
但是,在我们的任务中,我们必须处理字符串数组。 我试过了...
names[strlen(names[i])-1]='\0';
但似乎只能找到字符串的长度,减去 1,然后在索引中使用该数字,然后将字符串进一步设置为 \0
有没有办法访问字符串中的单个字符?
我知道我可以使用
访问字符串names[i] // where i is the numeric index
但我需要访问该字符串中的各个字符。
这是我第一次在 StackOverflow 上发帖,所以如果我没有包含足够的细节或问题的格式不正确,请通知我。
提前致谢。
最佳答案
如前所述,在 C 中,字符串是字符数组。因此,您可以像访问任何数组一样访问单个字符。对于你的任务,你需要做的是
char names[100][20];
//Now this declares 100 strings of size 20 each.
//To access a single character in the position '4' from string 0 you can write
printf("%c",names[0][3]);
//To modify the string in position 'i' you will use
names[i][strlen(names[i])-1]='\0';
最后一行与您为单个字符串编写的内容非常相似。
通过第一个索引“i”,您可以访问该位置的字符串。并使用第二个索引访问该字符串的特定字符。
关于c - 如何更改字符串数组中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829363/