c语言程序编写字符串应用
时间: 2025-01-27 08:39:44 浏览: 29
### C语言字符串操作编程示例
#### 将字符串转换为不同进制表示
在C语言中,可以编写函数将字符串中的字符逐个转换为其对应的ASCII码值,并进一步将其转换为不同的进制形式。
```c
#include <stdio.h>
#include <string.h>
void stringToBinary(const char *str) {
while (*str) {
printf("%d ", (unsigned int)*str);
str++;
}
}
int main() {
const char* testString = "ABC";
printf("The ASCII values of the characters in \"%s\" are:\n", testString);
stringToBinary(testString); // 输出每个字符的ASCII值[^1]
return 0;
}
```
此代码片段展示了如何遍历给定字符串并打印出各个字符所代表的ASCII数值。这一步骤对于理解后续向其他进制转化至关重要。
为了实现更复杂的转换功能,比如从十进制到二进制、八进制或十六进制,可利用标准库提供的`printf()`系列格式化输出函数:
```c
#include <stdio.h>
#include <stdlib.h>
void decimalToOtherBase(int num, int base) {
switch(base){
case 2 : printf("binary: %b\n", num); break; /* GCC扩展 */
case 8 : printf("octal: %#o\n", num); break;
case 16: printf("hexadecimal: %#x\n", num);break;
default: printf("Invalid Base!\n");
}
}
int main(){
unsigned char ch='A';
decimalToOtherBase(ch, 2); // 转换为二进制
decimalToOtherBase(ch, 8); // 转换为八进制
decimalToOtherBase(ch, 16); // 转换为十六进制
return 0;
}
```
请注意,在某些编译器上可能不支持直接使用 `%b` 来显示二进制数;此时可以选择自定义方法来完成这一任务。
#### 查找子串位置
当涉及到实际项目开发时,经常需要用到定位特定模式的位置等功能。下面给出了一种简单的方式——通过调用 `strstr()` 函数找到目标子串首次出现的地方:
```c
#include <stdio.h>
#include <string.h>
int findSubstringIndex(const char *haystack, const char *needle) {
const char *result = strstr(haystack, needle);
if(result != NULL)
return result - haystack;
return -1;
}
int main(void) {
char source[]="hello world!";
char target[]="world";
int index=findSubstringIndex(source,target);
if(index >= 0)
printf("\"%s\" found at position:%d.\n",target,index);
else
puts("Not Found!");
return 0;
}
```
这段程序能够有效地在一个较大的文本串(`source`)里寻找另一个较短的目标串(`target`)是否存在及其确切起始下标[^2]。
阅读全文
相关推荐


















