如何在某个位置打印字符串中的某个字符

  • 本文关键字:字符 字符串 位置 打印 c
  • 更新时间 :
  • 英文 :


是否有一种方法可以在某个位置打印字符串的指定字符?

例如:

char str[]="Hello";
Output:
o

我必须打印字母"o"在其索引指示的位置(在本例中为"4");

下面的4可以替换为04之间的任意数字

char kth = *(str + 4);
printf("n%c", kth);

输出:

o

这将打印出字符串中的第n个字符,并在左右两边填充空格

void print_nth_padded(const char *str, size_t n) {
for (size_t i = 0; i < n; i++) 
puts(" ");
printf("%c", str[n]);
for (size_t i = n + 1; i < strlen(str); i++)
puts(" ");
}

例如,print_nth_padded("Hello", 4);将打印出4个空格,后面跟着o

希望这段代码能有所帮助。它只是验证给定的索引是否有意义(如果它在数组的边界内),并在打印实际字符之前打印空格。

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

void print_char(const char * string, size_t index)
{
if (index >= strlen(string))
{
printf("The index is not correctn");
return;
}
size_t i = 0;
while (i < index)
{
printf(" ");
i++;
}
printf("%cn",string[i]);
}

注意:调用printf这么多次没有优化,但我认为留下这样的代码清晰。更优化的版本应该首先构造输出字符数组,并在准备好后打印它。

所以我们可以使用malloc来满足这个需求:

void print_char(const char * string, size_t index)
{
size_t buffer_size = strlen(string);
if (index >= strlen(string))
{
printf("The index is not correctn");
return;
}
char * buf = malloc(sizeof(char )* (buffer_size+1));
size_t i = 0;
while (i < index)
{
buf[i] = ' ';
i++;
}
buf[i] = string[i];
buf[i+1] = '';
//At this point your buffer is constructed
printf("%sn",buf);
free(buf);
}

可以有一个函数打印空格字符index次。当到达index时,显示该位置的字符。

void display(const char* str, const int index)
{
for (size_t i = 0; i < index; i++)
putc(' ', stdout);
putc(str[index], stdout);
}

请注意,您有责任验证index不超过字符数组的大小。例如,

const char str[] = "Hello";
size_t str_len = sizeof(str) / sizeof(str[0]);
const int index = 7;
if (index >= str_len || index <= 0) {
fprintf(stderr, "error: Attempted to access out-of-bound!n");
return EXIT_FAILURE;
}

如果我们考虑程序的完整版本,我们有:

#include <stdio.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
void display(const char* str, const int index)
{
for (size_t i = 0; i < index; i++)
putc(' ', stdout);
putc(str[index], stdout);
}
int main(void)
{
const char str[] = "Hello";
size_t str_len = sizeof str / sizeof str[0];
const int index = 4;
// Verification of the validity of the array index.
if (index >= str_len || index <= 0) {
fprintf(stderr, "error: Attempted to access out-of-bound!n");
return EXIT_FAILURE;
}
// Calling the function safely.
display(str, index);
return EXIT_SUCCESS;
}

现在,我们有以下输出:

$ gcc -std=c99 -g 1.c && ./a.out
o

使用指定的字符查找其在字符串中的位置。

char str[]="Hello";
char specified_character = 'o';
char *position = strchr(str, specified_character);

如果找到,通过传入宽度打印左侧' '填充的字符。

if (position) {
int padding = position - str;
int width = padding + 1;
printf("%*cn", width, str[padding]);
}

输出:o