/* 題目:在字符串中找出第一個只出現一次的字符。
* 如輸入“abaccdeff”,則輸出'b'。
*/
#include<stdio.h>
#include<stdlib.h>
int find_f(char arr[],const int len) //尋找函數
{
int i, j, k;
int arr1[20] = { 0 }; //定義一個儲存每個字符出現次數的數組,
for (i = 0; i < len; i++) //對字符數組元素進行遍歷,並記錄該字符出現次數
{
k = 0;
for (j = 0; j < len; j++)
{
if (arr[i] == arr[j])
k++;
arr1[i] = k;
}
}
for (i = 0; i < len; i++) //從第一個開始訪問,找出第一個只出現一次的字符,返回該字符在原數組的下標
{
if (arr1[i] == 1)
{
return i;
}
}
return len + 1; //如果沒有單獨出現的字符,返回一個不是下標的數
}
int main()
{
char arr[] = "abaccdeff";
int len = sizeof(arr) / sizeof(arr[0]), c;
c = find_f(arr, len);
if (c > len)
printf("這個字符串組數中沒有只出現一次的字符\n");
else
printf("輸入字符串中第一次出現的字符是:%c\n", arr[c]);
system("pause");
return 0;
}
方法二:當字符數組比較大時,記錄每個字符出現的個數(用哈希表,具體方法:我們第一遍掃描這個數組時,每碰到一個字符,在哈希表中找到對應的項並把出現的次數增加一次。這樣在進行第二次掃描時,就能直接從哈希表中得到每個字符出現的次數了。) 代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define tableSize 256 //創建一個哈希表,因為ASCII碼表中只有0~255共256個字符。
char First_Char(char* pString)
{
if (!pString) //輸入不合法
return 0;
int hashTable[tableSize];
for (int i = 0; i < tableSize; i++)
hashTable[i] = 0;
//確定字符串中每個字符出現的次數
char* pHashKey = pString;
while (*(pHashKey) != '\0')
hashTable[*(pHashKey++)]++;
//找到字符串中只出現一次的那個字符
pHashKey = pString;
while (*pHashKey != '\0')
{
if (hashTable[*pHashKey] == 1)
return*pHashKey;
pHashKey++;
}
//如果這個字符串為空,或者字符串中的每個字符都至少出現兩次
return 0;
}
int main(void)
{
char str[1000]; //這個函數是在字符串特別大時建議使用,故定義一個大小為1000的數組
printf("請輸入字符串:");
gets(str);
if (First_Char(str) == 0)
printf("輸入字符串中沒有找到第一個只出現一次的字符!\n");
else
printf("輸入字符串中第一個只出現一次的字符為:%c\n", First_Char(str));
system("pause");
return 0;
}